Home > Blockchain >  How to find unique value from an array in sorted order using for loop and sort() in javascript?
How to find unique value from an array in sorted order using for loop and sort() in javascript?

Time:05-19

My array is:

const arr = [1, 4, 8, 10, 5, 7, 5, 9, 7, 5, 44, 6]

CodePudding user response:

This is how you could go about sorting your array:

const arr = [1, 5, 7, 44, 5, 9, 4, 5, 9, 10, 6, 7, 8];

const uniqueArr = arr.filter(function(item, idx, self) {
    return self.indexOf(item) == idx;
})

const sortedArr = uniqueArr.sort(function(a, b) {
    return a - b;
});
console.log(sortedArr);

CodePudding user response:

const arr = [1, 4, 8, 10, 5, 7, 5, 9, 7, 5, 44, 6];
      arr.sort((a,b) => {return a - b;});
let len = arr.length;
const unique = [];

for(let i = 0; i < len; i  ){
  if(unique.indexOf(arr[i]) === -1){
     unique.push(arr[i]);
  }
}

console.log(unique);
  • Related