5

Possible Duplicate:
How to sort an array of javascript objects?

How to sort list of dicts in js?

I have:

[{'car': 'UAZ', 'price': 30 ,'currency': 'RUB'}, {'car': 'Mazda', 'price': 1000 ,'currency': 'USD'},{'car': 'Zaporozhec', 'price': 2 ,'currency': 'RUB'}, {'car': 'GAZ', 'price': 0 ,'currency': 'RUB'}]

I want to have it sorted by price and currency:

[{'car': 'Mazda', 'price': 1000 ,'currency': 'USD'}, {'car': 'UAZ', 'price': 30 ,'currency': 'RUB'},{'car': 'Zaporozhec', 'price': 2 ,'currency': 'RUB'}, {'car': 'GAZ', 'price': 0 ,'currency': 'RUB'}]
Community
  • 1
  • 1
Pavel Shevelyov
  • 61
  • 1
  • 2
  • 3

2 Answers2

11
yourArrayOfObjects.sort(function(first, second) {
 return second.price - first.price;
});
fardjad
  • 20,031
  • 6
  • 53
  • 68
2

JavaScript isn't Python. You have an array of objects there.

Call the array sort method. Pass it a function that takes two arguments (the two objects in the array that are being compared). Have it return -1, 0, or 1 depending on which order you want those two objects to be sorted into (there are examples and more detail in the documentation I linked to above).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335