Using Javascript to sort an array of numeric arrays

不想你离开。 提交于 2019-12-05 06:27:32

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.

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

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

You need to sort and compare between the 2 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);

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

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

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

This is simplest way i think, it's worked.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!