Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 521
theHack Avatar asked Jan 28 '11 22:01

theHack


People also ask

Does sort mutate array JavaScript?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.

How JavaScript array sort works?

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.


2 Answers

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"] 
like image 168
lonesomeday Avatar answered Oct 01 '22 03:10

lonesomeday


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)}) 
like image 27
mrmonkington Avatar answered Oct 01 '22 04:10

mrmonkington