2

我知道这个问题在这个社区已经被问过很多次了,但我几乎看不到笔记本电脑的显示器,因为我工作了很长时间。一些帮助请。

我想对这个对象数组进行排序,以获得自动插入到数组中的所有给定值的最大值和最小值。

var catesArrayHolder = new Array();
for(var chartGetter=1; chartGetter <= num; chartGetter++){
    var catesArray = new Array();
    for(var chartGetterArray=1; chartGetterArray <= series; chartGetterArray++){
        idOfInput  = "cate"+chartGetter+"_series"+chartGetterArray;
        values = $("#"+idOfInput).val();
        if(values == ""){
            values = 0;
        }

        catesArray.push(values);
    }
    catesArrayHolder.push(catesArray);
}

此功能不适用于我...它适用于一维数组

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

我感谢您的帮助。

4

1 回答 1

2

Edit

To sort on the Sum of the sub arrays you can use:

Example

JS

var twoDArray = [[9,1],[5,3],[8,2]];

twoDArray.sort(function(a, b){
    //sort by sum of sub array
    return eval(a.join('+')) - eval(b.join('+')); 
}); 

alert(JSON.stringify(twoDArray)); 

So your code would look like:

catesArrayHolder.sort(function(a, b){
    return eval(a.join('+')) - eval(b.join('+')); 
}); 

Original

Looks like you're trying to sort a two dimensional array.

You'll need to specify the secondary array position in the sort function.

Example

JS

var twoDArray = [[9,1],[5,3],[4,2]];

twoDArray.sort(function(a, b){
    //Sort by the first value in the sub array
    return a[0] - b[0]; 
}); 

alert(JSON.stringify(twoDArray)); 

twoDArray.sort(function(a, b){
    //sort by the second value in the sub array
    return a[1] - b[1]; 
}); 

alert(JSON.stringify(twoDArray)); 

So to get your code working, you'll need something to the effect of:

var posToSortOn = 0; //position in the sub arrays that dictates sort precedence 
catesArrayHolder.sort(function(a,b){return a[posToSortOn]-b[posToSortOn]});
于 2013-02-28T03:43:04.510 回答