1

在参照此贴;我可以按 2 个字段对 JSON 对象数组进行排序。这个帖子还指出:

“要添加其他列进行排序,您可以在数组比较中添加其他项目。”

//THIS WORKS BUT NEEDS TO SORT BY ALL 5 FIELDS..
function sortRecords(a, b){
//note the minus before -cmp, for descending order
// field1 (Y or N), field2 (numeric), field3 (numeric), 
// field4 (Y or N), field5 (Y or N)
return cmp( 
    [-cmp(a.field1, b.field1), cmp(a.field2, b.field2)], 
    [-cmp(b.field1, a.field1), cmp(b.field2, a.field2)]
 );}

//THIS ONLY SORTS BY field1 and field2
function sortRecords(a, b){
//note the minus before -cmp, for descending order
// field1 (Y or N), field2 (numeric), field3 (numeric), 
// field4 (Y or N), field5 (Y or N)
return cmp( 
    [-cmp(a.field1, b.field1), cmp(a.field2, b.field2), cmp(a.field3, b.field3)], 
    [-cmp(b.field1, a.field1), cmp(b.field2, a.field2), cmp(b.field3, a.field3)]
 );}

function cmp(x,y){
return x > y ? 1 : x < y ? -1 : 0;
}


///implementation
data = $(data).sort(sortRecords);

我在这里做错了什么?

4

1 回答 1

0

我一直在使用 StackOverflow,并结合了几个如何排序/排序的示例;这个功能似乎给了我我正在寻找的东西......

给定这个 JSON 对象数组为[data]

{"name":"JOE","field1":"Y","field2":3,"field3":79," field4 ":"Y","field5":"Y"} {"name" :"BEN","field1":"Y","field2":15,"field3":113,"field4":"Y","field5":"N"} {"name":"SUE", "field1":"Y","field2":35,"field3":395,"field4":"Y","field5":"Y"}

我可以调用 sortRecords() 来排序我想要的。

{"name":"JOE","field1":"Y","field2":3,"field3":79," field4 ":"Y","field5":"Y"} {"name" :"SUE","field1":"Y","field2":35,"field3":395,"field4":"Y","field5":"Y"} {"name":"BEN", "field1":"Y","field2":15,"field3":113,"field4":"Y","field5":"N"}

function sortRecords(a, b){
    if (a.field1 < b.field1){
        return 1;
    } else if (a.field1 > b.field1){
        return -1;
    } else if (a.field2 < b.field2){
        return 1;
    } else if (a.field2 > b.field2){
        return -1;
    } else if (a.field3 < b.field3){
        return 1;
    } else if (a.field3 > b.field3){
        return -1;
    } else if (a.field4 < b.field4){
        return -1;
    } else if (a.field4 > b.field4){
        return 1;
    } else if (a.field5 < b.field5){
        return -1;
    } else if (a.field5 > b.field5){
        return 1;
    } else {
        return 0;
    }
}

data = $(data).sort(sortRecords);
于 2012-12-11T18:18:24.920 回答