我使用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属性按升序或降序对对象进行排序?
要对数组进行排序,必须定义一个比较器函数。此函数始终根据您所需的排序模式或顺序(即升序或降序)而不同。
让我们创建一些函数,对数组进行升序或降序排序,并包含对象、字符串或数值。
function sorterAscending(a,b) {
return a-b;
}
function sorterDescending(a,b) {
return b-a;
}
function sorterPriceAsc(a,b) {
return parseInt(a['price']) - parseInt(b['price']);
}
function sorterPriceDes(a,b) {
return parseInt(b['price']) - parseInt(b['price']);
}
排序数字(按字母顺序和升序):
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
排序数字(按字母顺序和降序):
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
排序编号(数字和升序):
var points = [40,100,1,5,25,10];
points.sort(sorterAscending());
排序编号(数字和降序):
var points = [40,100,1,5,25,10];
points.sort(sorterDescending());
如上所述,将sorterPriceAsc和sorterPriceDes方法用于具有所需键的数组。
homes.sort(sorterPriceAsc()) or homes.sort(sorterPriceDes())
更像LINQ的解决方案:
Array.prototype.orderBy = function (selector, desc = false) {
return [...this].sort((a, b) => {
a = selector(a);
b = selector(b);
if (a == b) return 0;
return (desc ? a > b : a < b) ? -1 : 1;
});
}
优势:
财产的自动补全扩展阵列原型不更改数组易于在方法链中使用
用法:
Array.prototype.orderBy=函数(选择器,desc=false){return[…this].sort((a,b)=>{a=选择器(a);b=选择器(b);如果(a==b)返回0;返回(desc?a>b:a<b)-1 : 1;});};var家=[{“h_id”:“3”,“城市”:“达拉斯”,“状态”:“TX”,“zip”:“75201”,“价格”:“162500”}, {“h_id”:“4”,“城市”:“贝弗利山”,“状态”:“CA”,“zip”:“90210”,“price”:“319250”}, {“h_id”:“5”,“城市”:“纽约”,“州”:“NY”,“zip”:“00010”,“价格”:“962500”}];let sorted_homes=homes.orderBy(h=>parseFloat(h.price));console.log(“按价格排序”,sorted_homes);let sorted_homes_desc=homes.orderBy(h=>h.city,true);console.log(“按城市降序排序”,sorted_home_desc);
我最近编写了一个通用函数,如果您想使用它,可以为您管理它。
/**
* Sorts an object into an order
*
* @require jQuery
*
* @param object Our JSON object to sort
* @param type Only alphabetical at the moment
* @param identifier The array or object key to sort by
* @param order Ascending or Descending
*
* @returns Array
*/
function sortItems(object, type, identifier, order){
var returnedArray = [];
var emptiesArray = []; // An array for all of our empty cans
// Convert the given object to an array
$.each(object, function(key, object){
// Store all of our empty cans in their own array
// Store all other objects in our returned array
object[identifier] == null ? emptiesArray.push(object) : returnedArray.push(object);
});
// Sort the array based on the type given
switch(type){
case 'alphabetical':
returnedArray.sort(function(a, b){
return(a[identifier] == b[identifier]) ? 0 : (
// Sort ascending or descending based on order given
order == 'asc' ? a[identifier] > b[identifier] : a[identifier] < b[identifier]
) ? 1 : -1;
});
break;
default:
}
// Return our sorted array along with the empties at the bottom depending on sort order
return order == 'asc' ? returnedArray.concat(emptiesArray) : emptiesArray.concat(returnedArray);
}
使用此函数
const r_sort = (a, b, field, asc) => {
let reverse = asc ? 1 : -1;
if (a[field] > b[field]) {
return 1 * reverse;
}
else if (b[field] > a[field]) {
return -1 * reverse;
}
else {
return 0;
} }
//用法:
homes = homes.sort((a,b) => r_sort(a,b,price,true)) // true for ascending and false for descending