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?


Solution 1:

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"]

Solution 2:

This might be adequate in circumstances where you can't define the function in advance (like in a bookmarklet):

myData.sort().filter(function(el,i,a){return i===a.indexOf(el)})

Solution 3:

You can now achieve the result in just one line of code.

Using new Set to reduce the array to unique set of values. Apply the sort method after to order the string values.

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

var uniqueAndSorted = [...new Set(myData)].sort() 

UPDATED for newer methods introduced in JavaScript since time of question.

Solution 4:

Here's my (more modern) approach using Array.protoype.reduce():

[2, 1, 2, 3].reduce((a, x) => a.includes(x) ? a : [...a, x], []).sort()
// returns [1, 2, 3]

Edit: More performant version as pointed out in the comments:

arr.sort().filter((x, i, a) => !i || x != a[i-1])