小编典典

JavaScript 按属性值对对象数组进行排序

javascript

我已经使用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属性 升序 降序 对对象进行排序?


阅读 355

收藏
2020-04-22

共1个答案

小编典典

按价格升序对房屋进行排序:

homes.sort(function(a, b) {
    return parseFloat(a.price) - parseFloat(b.price);
});

或在ES6版本之后:

homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
2020-04-22