Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list of dicts in js? [duplicate]

Tags:

javascript

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'}]
like image 306
Pavel Shevelyov Avatar asked Nov 11 '11 10:11

Pavel Shevelyov


2 Answers

yourArrayOfObjects.sort(function(first, second) {
 return second.price - first.price;
});
like image 67
fardjad Avatar answered Oct 18 '22 03:10

fardjad


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).

like image 42
Quentin Avatar answered Oct 18 '22 04:10

Quentin