4 回答

TA贡献1827条经验 获得超9个赞
这是一个更灵活的版本,它允许您创建可重复使用的排序函数,并按任何字段排序。
var sort_by = function(field, reverse, primer){
var key = primer ?
function(x) {return primer(x[field])} :
function(x) {return x[field]};
reverse = !reverse ? 1 : -1;
return function (a, b) {
return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
}
}
现在您可以随意按任意字段排序......
var homes = [{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
}, {
"h_id": "4",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}];
// Sort by price high to low
homes.sort(sort_by('price', true, parseInt));
// Sort by city, case-insensitive, A-Z
homes.sort(sort_by('city', false, function(a){return a.toUpperCase()}));

TA贡献1817条经验 获得超6个赞
要对它进行排序,您需要创建一个带有两个参数的比较器函数。然后使用该比较器函数调用sort函数,如下所示:
// a and b are object elements of your arrayfunction mycomparator(a,b) { return parseInt(a.price, 10) - parseInt(b.price, 10);}homes.sort(mycomparator);
如果要对升序进行排序,请在减号的每一侧切换表达式。

TA贡献1815条经验 获得超10个赞
对于字符串排序,如果有人需要它,
var dataArr = { "hello": [{ "id": 114, "keyword": "zzzzzz", "region": "Sri Lanka", "supportGroup": "administrators", "category": "Category2"}, { "id": 115, "keyword": "aaaaa", "region": "Japan", "supportGroup": "developers", "category": "Category2"}]};var sortArray = dataArr['hello'];sortArray.sort(function(a,b) { if ( a.region < b.region ) return -1; if ( a.region > b.region ) return 1; return 0;} );
添加回答
举报