在 JavaScript 中按价格对数组进行排序
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 11:56:17
假设我们有一个对象数组,其中包含一些房屋和价格的数据,如下所示 −
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 函数来接收一个这样的数组。该函数应该根据对象的价格属性(当前为字符串)对数组进行排序(升序或降序)。
示例
其代码为 −
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'
}
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

