3

我通常会发布到目前为止的代码,但我对此一无所知... :(

我将如何重新排序以下数组,以便我可以基于“百分比”键中的值,无论是从低到高还是从高到低?

var data = [{
    "id": "q1",
    "question": "blah blah blah",
    "percentage": "32"
}, {
    "id": "q2",
    "question": "blah blah blah",
    "percentage": "23"
}, {
    "id": "q3",
    "question": "blah blah blah",
    "percentage": "11"
}, {
    "id": "q4",
    "question": "blah blah blah",
    "percentage": "3"
}, {
    "id": "q5",
    "question": "blah blah blah",
    "percentage": "6"
}]
4

3 回答 3

5

稍微更正一下,它不是多维数组,而是对象数组,您很可能混淆了 from 的命名,对于您的问题,请使用sortPHP的可选函数参数来定义您自己的排序顺序。

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

// sorted data, no need to do data = data.sort(...);

http://jsfiddle.net/cEfRd/

于 2012-05-31T05:48:38.727 回答
4

排序器生成器,概括https://stackoverflow.com/users/135448/siganteng答案,使其适用于任何属性

function  createSorter(propName) {
    return function (a,b) {
        // The following won't work for strings
        // return a[propName] - b[propName];
        var aVal = a[propName], bVal = b[propName] ;
        return aVal > bVal ? 1 : (aVal < bVal ?  - 1 : 0);

    };
}
data.sort(createSorter('percentage'));
于 2012-05-31T05:55:37.553 回答
2
data.sort(function(a,b){return a.percentage - b.percentage});

参考。_

于 2012-05-31T05:49:54.247 回答