我使用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())
我还处理了一些评级和多个字段排序:
arr = [
{type:'C', note:834},
{type:'D', note:732},
{type:'D', note:008},
{type:'F', note:474},
{type:'P', note:283},
{type:'P', note:165},
{type:'X', note:173},
{type:'Z', note:239},
];
arr.sort(function(a,b){
var _a = ((a.type==='C')?'0':(a.type==='P')?'1':'2');
_a += (a.type.localeCompare(b.type)===-1)?'0':'1';
_a += (a.note>b.note)?'1':'0';
var _b = ((b.type==='C')?'0':(b.type==='P')?'1':'2');
_b += (b.type.localeCompare(a.type)===-1)?'0':'1';
_b += (b.note>a.note)?'1':'0';
return parseInt(_a) - parseInt(_b);
});
后果
[
{"type":"C","note":834},
{"type":"P","note":165},
{"type":"P","note":283},
{"type":"D","note":8},
{"type":"D","note":732},
{"type":"F","note":474},
{"type":"X","note":173},
{"type":"Z","note":239}
]
仅对于元素值的普通数组:
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}]
使用此函数
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