按属性值对对象数组进行排序-JavaScript
假设我们有一个像这样的对象数组-
const 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属性按升序或降序对对象进行排序。
示例
以下是代码-
const 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"
}
];
const sortByPrice = arr => {
arr.sort((a, b) => {
return parseFloat(a.price) - parseFloat(b.price);
});
};
sortByPrice(homes);
console.log(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 的全部内容, 来源链接: utcz.com/z/345649.html