我使用 Ajax 读取以下对象并将它们存储在一个数组中:
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"
}
];
如何使用 JavaScript 创建一个函数来按price
属性按升序 或 降序对对象进行排序?
按价格按升序排序房屋:
homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
或者在 ES6 版本之后:
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
有些文档可以在这里找到。
这是一个更灵活的版本,它允许您创建可重复使用的排序函数,并按任何字段排序。
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()}));
要对它进行排序,您需要创建一个带有两个参数的比较器函数。然后使用该比较器函数调用 sort 函数,如下所示:
// a and b are object elements of your array
function mycomparator(a,b) {
return parseInt(a.price, 10) - parseInt(b.price, 10);
}
homes.sort(mycomparator);
如果要对升序进行排序,请在减号的每一侧切换表达式。