jagershark
jagershark

Reputation: 1241

Sort javascript array of objects

I have a array that looks like this:

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

I want to sort the array in descending order by the 'amount' value, so once sorted, the array would look like this:

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

I've seen various posts similar to this on stackoverflow, but I find it hard to interpret those problems to one like mine which has named indexes (name, amount, colour) rather than just [0], [1], [2] etc.

Upvotes: 2

Views: 82

Answers (1)

ZER0
ZER0

Reputation: 25322

Use Array.sort:

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

Upvotes: 2

Related Questions