2

我有一个看起来像这样的数组:

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"}
]

我想按“数量”值对数组进行降序排序,因此排序后,数组将如下所示:

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]等的问题。

4

1 回答 1

3

使用Array.sort

data.sort(function(a, b) {
    return b.amount - a.amount;
});
于 2013-03-02T16:04:05.190 回答