Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript to sort an array of numeric arrays

In Javascript, if I have an array of arrays, like the following:

X = [ [1,2,3,4],
      [1,1,2,3],
      [1,1,3],
      [1,4],
      [2,1,2],
      [2,2]
    ]

Javascript sorts my array, comparing first entry first, then second, and so on, so that X.sort() returns the following:

[ [1,1,2,3],
  [1,1,3],
  [1,2,3,4],
  [1,4],
  [2,1,2],
  [2,2]
]

Which is what I want. The problem is that the comparison operator for comparing the elements in the arrays is lexicographical, so [10,2] < [2,2], and, for example,

[[10,2],[1,1,3],[2,2]].sort() -> [[1,1,3],[10,2],[2,2]]

I need it to sort numerically, so that I get a sorted array of [[1,1,3],[2,2],[10,2]].

I tried using a comparison function of function(a,b){return (a-b) }, which would work for sorting an array of numbers, but this fails to properly sort my array, which makes sense (I think) because [10,2] - [1,1,3] yields NaN

How do I go about sorting an array of numeric arrays?

like image 238
ckersch Avatar asked Mar 28 '13 15:03

ckersch


People also ask

Can you sort an array of arrays JavaScript?

To sort an array of arrays in JavaScript, we can use the array sort method. We call array. sort with a callback that destructures the first entry from each nested array. Then we return the value to determine how it's sorted.

How do you sort an array of numbers in numerical manner?

We can use . sort((a,b)=>a-b) to sort an array of numbers in ascending numerical order or . sort((a,b)=>b-a) for descending order.

How do you sort a number in an array of strings?

sort() Method. In Java, Arrays is the class defined in the java. util package that provides sort() method to sort an array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting.


3 Answers

As I said in my comment, the sort function needs to account for the fact that it's receiving arrays as arguments and not plain values. So you need to handle them accordingly.

I suggest this;

var compFunc = function (a, b) {
    var len = a.length > b.length ? b.length : a.length;

    for(var i=0; i<len; ++i) {
        if(a[i] - b[i] !== 0)
            return a[i] - b[i];
    }

    return (a.length - b.length);
};

It first tries to look for differences in the common length of the two arrays. If the common length is exactly the same, then it sorts on the basis of array length. Here's a working fiddle.

like image 155
Rikonator Avatar answered Sep 19 '22 00:09

Rikonator


What you want is to run a natural sort. For your compare function, replace it with the script mentioned in this article

http://my.opera.com/GreyWyvern/blog/show.dml/1671288

like image 25
75inchpianist Avatar answered Sep 22 '22 00:09

75inchpianist


When you do X.sort(), Javascript is comparing your individual arrays as strings. It's basically doing a.toString().localeCompare(b.toString()). This is not what you want.

a.toString() is usually the same as a.join(',')

What I would do is compare each element in the arrays by using a for loop.

Something like this:

X.sort(function(a,b){
    // Start off assuming values are equal
    var ret = 0;

    // Loop through a
    for(var a_i = 0, a_length = a.length; a_i < a_length; a_i++){
        // If b is shorter than a, it comes first
        if(typeof b[a_i] === 'undefined'){
            ret = 1;
            break;
        }
        // if the element in a and b are *not* the same, then we can sort
        else if(a[a_i] !== b[a_i]){
            ret = a[a_i] - b[a_i];
            break;
        }
    }

    return ret;
});
like image 32
Rocket Hazmat Avatar answered Sep 21 '22 00:09

Rocket Hazmat