Using Javascript to sort an array of numeric arrays

In Javascript, if I have an array of arrays, for example:

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

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

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

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

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

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

I tried to use a comparison function function(a,b){return (a-b) }that will work for sorting an array of numbers, but this does not allow me to sort my array correctly, which makes sense (I think) because it [10,2] - [1,1,3]givesNaN

How do I sort an array of numeric arrays?

+5
5

, sort , , . .

;

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);
};

. , . .

+6

X.sort(), Javascript . a.toString().localeCompare(b.toString()). , .

a.toString() a.join(',')

, for.

- :

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;
});
+1

You need to sort and compare between two arrays: http://jsfiddle.net/pXzB6/

var arr = [[10,2],[1,1,3],[2,2]];

arr.sort(function(a,b){
    for(var i=0;i<a.length;i++){
       var item_a = a[i];
       for(var j=0;j<b.length;b++){   
           var item_b = b[j];   
           if(item_a == item_b){
                 continue;
           }
           else{
               return item_a > item_b;
           }
       }
    }

    if(a.length == b.length){
       return 0;
    }
    else{
      return a.length > b.length;
    }
});

console.log(arr);
0
source

var points = [40, 100, 1, 5, 25, 10];

points.sort (function (a, b) {return ab});

then the result: 1,5,10,25,40,100

This is the easiest way, I think it worked.

0
source

All Articles