排序javascript对象数组

时间:2013-03-02 15:55:52

标签: javascript sorting

我有一个如下所示的数组:

data = 
[
    {name: "Monday", amount: 67, colour: "red"},

    {name: "Tuesday", amount: 23, colour: "blue"},

    {name: "Wednesday", amount: 50, colour: "yellow"},

    {name: "Thursday", amount: 70, colour: "green"},

    {name: "Friday", amount: 20, colour: "orange"},

    {name: "Saturday", amount: 90, colour: "black"},

    {name: "Sunday", amount: 10, colour: "brown"}
]

我想按'amount'值按降序对数组进行排序,因此一旦排序,数组将如下所示:

data = 
[
    {name: "Saturday", amount: 90, colour: "black"},

    {name: "Thursday", amount: 70, colour: "green"},

    {name: "Monday", amount: 67, colour: "red"},

    {name: "Wednesday", amount: 50, colour: "yellow"},

    {name: "Tuesday", amount: 23, colour: "blue"},

    {name: "Friday", amount: 20, colour: "orange"},

    {name: "Sunday", amount: 10, colour: "brown"}
]

我在stackoverflow上看到了类似的各种帖子,但是我发现很难将这些问题解释为像我这样的问题索引(名称,数量,颜色),而不仅仅是[0], [1], [2]等。 / p>

1 个答案:

答案 0 :(得分:3)

使用Array.sort

data.sort(function(a, b) {
    return b.amount - a.amount;
});