javascript tutorial - [Solved-5 Solutions] Sort array of objects by string property value in javascript
- javascript - java script - javascript array
Problem:
We have an array of JavaScript objects:
How can we sort them by the value of last_nom in JavaScript ? we know about sort(a,b), but that only seems to work on strings and numbers. Do you need to add a toString method to my objects ?
Solution 1:
It's easy enough to write our own comparison function:
Or inline (c/o Marco Demaio):
Solution 2:
use underscore, its small and awesome...
sortBy_.sortBy(list, iterator, [context]) Returns a sorted copy of list, ranked in ascending order by the results of running each value through iterator. Iterator may also be the string name of the property to sort by (eg. length).
Solution 3:
Don't get why people make it so complicated:
Swap the operator to have it sorted by reverse alphabetical order.
Solution 4:
In ES6/ES2015 or later we can do this way:
Solution 5:
If we have duplicate last names we might sort those by first name-