ckersch ckersch - 1 year ago 74
Javascript Question

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

Javascript sorts my array, comparing first entry first, then second, and so on, so that
returns the following:

[ [1,1,2,3],

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

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]

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download