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'}]
yourArrayOfObjects.sort(function(first, second) {
return second.price - first.price;
});
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With