我使用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 desc(a, b) {
return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}
function asc(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
然后可以将其应用于任何对象属性:
data.sort((a, b) => desc(parseFloat(a.price), parseFloat(b.price)));
让数据=[{label:“一”,值:10},{label:“two”,值:5},{label:“three”,值:1},];//排序函数函数desc(a,b){返回b<a-1:b>a?1:b>=a?0:NaN;}函数asc(a,b){返回a<b-1:a>b?1:a>=b?0:NaN;}//描述(DESC)data.sort((a,b)=>desc(a.value,b.value));document.body.insert相邻HTML('之前','<strong>DESC排序</strong><pre>'+JSON.stringify(数据)+'</pre>');//美国科学院data.sort((a,b)=>asc(a.value,b.value));document.body.insert相邻HTML('之前','<strong>ASCending sorted</strong><pre>'+JSON.stringify(数据)+'</pre>');
这里是以上所有答案的顶点。
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();
}));
}
}
仅对于元素值的普通数组:
function sortArrayOfElements(arrayToSort) {
function compareElements(a, b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
return arrayToSort.sort(compareElements);
}
e.g. 1:
var array1 = [1,2,545,676,64,2,24]
output : [1, 2, 2, 24, 64, 545, 676]
var array2 = ["v","a",545,676,64,2,"24"]
output: ["a", "v", 2, "24", 64, 545, 676]
对于对象数组:
function sortArrayOfObjects(arrayToSort, key) {
function compareObjects(a, b) {
if (a[key] < b[key])
return -1;
if (a[key] > b[key])
return 1;
return 0;
}
return arrayToSort.sort(compareObjects);
}
e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]
output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]