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.

jagershark
  • 1,162
  • 3
  • 15
  • 27
  • 1
    Search for "sort array of objects" instead. There are no "arrays with named indizes", and you don't have a "multidimensional array". – Bergi Mar 02 '13 at 16:07
  • possible duplicate of [How to sort an array of javascript objects?](http://stackoverflow.com/questions/979256/how-to-sort-an-array-of-javascript-objects) – Bergi Mar 02 '13 at 16:09
  • 1
    You have an array of objects, not a multidimensional array. – Mike Valenty Mar 02 '13 at 16:17

1 Answers1

3

Use Array.sort:

data.sort(function(a, b) {
    return b.amount - a.amount;
});
ZER0
  • 24,846
  • 5
  • 51
  • 54