Skip to content
Advertisement

Javascript array sort and unique

I have a JavaScript array like this:

var myData=['237','124','255','124','366','255'];

I need the array elements to be unique and sorted:

myData[0]='124';
myData[1]='237';
myData[2]='255';
myData[3]='366';

Even though the members of array look like integers, they’re not integers, since I have already converted each to be string:

var myData[0]=num.toString();
//...and so on.

Is there any way to do all of these tasks in JavaScript?

Advertisement

Answer

This is actually very simple. It is much easier to find unique values, if the values are sorted first:

function sort_unique(arr) {
  if (arr.length === 0) return arr;
  arr = arr.sort(function (a, b) { return a*1 - b*1; });
  var ret = [arr[0]];
  for (var i = 1; i < arr.length; i++) { //Start loop at 1: arr[0] can never be a duplicate
    if (arr[i-1] !== arr[i]) {
      ret.push(arr[i]);
    }
  }
  return ret;
}
console.log(sort_unique(['237','124','255','124','366','255']));
//["124", "237", "255", "366"]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement