2

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.

3
  • 1
    Search for "sort array of objects" instead. There are no "arrays with named indizes", and you don't have a "multidimensional array".
    – Bergi
    Commented Mar 2, 2013 at 16:07
  • possible duplicate of How to sort an array of javascript objects?
    – Bergi
    Commented Mar 2, 2013 at 16:09
  • 1
    You have an array of objects, not a multidimensional array. Commented Mar 2, 2013 at 16:17

1 Answer 1

2

Use Array.sort:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.