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?
The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.
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"]
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)})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With