在JavaScript中按价格对数组进行排序
假设我们有一个对象数组,其中包含有关某些房屋和价格的数据,如下所示:
const arr = [
{
"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属性对数组进行排序(升序或降序)。
示例
为此的代码将是-
const arr = [
{
"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"
}
];
const eitherSort = (arr = []) => {
const sorter = (a, b) => {
return +a.price - +b.price;
};
arr.sort(sorter);
};
eitherSort(arr);
console.log(arr);输出结果
控制台中的输出将是-
[
{
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'
}
]热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短