我使用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属性按升序或降序对对象进行排序?
这里是以上所有答案的顶点。
Fiddle验证:http://jsfiddle.net/bobberino/4qqk3/
var sortOn = function (arr, prop, reverse, numeric) {
// Ensure there's a property
if (!prop || !arr) {
return arr
}
// Set up sort function
var sort_by = function (field, rev, primer) {
// Return the required a,b function
return function (a, b) {
// Reset a, b to the field
a = primer(a[field]), b = primer(b[field]);
// Do actual sorting, reverse as needed
return ((a < b) ? -1 : ((a > b) ? 1 : 0)) * (rev ? -1 : 1);
}
}
// Distinguish between numeric and string to prevent 100's from coming before smaller
// e.g.
// 1
// 20
// 3
// 4000
// 50
if (numeric) {
// Do sort "in place" with sort_by function
arr.sort(sort_by(prop, reverse, function (a) {
// - Force value to a string.
// - Replace any non numeric characters.
// - Parse as float to allow 0.02 values.
return parseFloat(String(a).replace(/[^0-9.-]+/g, ''));
}));
} else {
// Do sort "in place" with sort_by function
arr.sort(sort_by(prop, reverse, function (a) {
// - Force value to string.
return String(a).toUpperCase();
}));
}
}
使用以下代码创建函数并根据输入进行排序
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"
}];
function sortList(list,order){
if(order=="ASC"){
return list.sort((a,b)=>{
return parseFloat(a.price) - parseFloat(b.price);
})
}
else{
return list.sort((a,b)=>{
return parseFloat(b.price) - parseFloat(a.price);
});
}
}
sortList(homes,'DESC');
console.log(homes);