按属性值对对象数组进行排序 [英] Sorting an array of objects by property values

查看:105
本文介绍了按属性值对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用AJAX获得了以下对象并将它们存储在数组中:

I've got the following objects using AJAX and stored them in an array:

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属性对对象进行排序的函数?

How do I create a function to sort the objects by the price property in ascending or descending order using JavaScript only?

推荐答案

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

Sort homes by price in ascending order:

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

或在ES6版本之后:

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

可以在此处找到一些文档

对于降序,可以使用

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

这篇关于按属性值对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆