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

2 Answers2

10
yourArrayOfObjects.sort(function(first, second) {
 return second.price - first.price;
});
fardjad
  • 19,236
  • 6
  • 50
  • 67
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
  • 857,932
  • 118
  • 1,152
  • 1,264