I got an array (see below for one object in the array) that I need to sort by firstname using JavaScript. How can I do it?
var user = { bio: null, email: "[email protected]", firstname: "Anna", id: 318, lastAvatar: null, lastMessage: null, lastname: "Nickson", nickname: "anny" };
JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
In JavaScript arrays have a sort( ) method that sorts the array items into an alphabetical order. The sort( ) method accepts an optional argument which is a function that compares two elements of the array. If the compare function is omitted, then the sort( ) method will sort the element based on the elements values.
The sort() method sorts the strings in alphabetical and ascending order. The for...of loop is used to iterate over the array elements and display them.
Shortest possible code with ES6!
users.sort((a, b) => a.firstname.localeCompare(b.firstname))
String.prototype.localeCompare() basic support is universal!
Suppose you have an array users
. You may use users.sort
and pass a function that takes two arguments and compare them (comparator)
It should return
In our case if two elements are a
and b
we want to compare a.firstname
and b.firstname
Example:
users.sort(function(a, b){ if(a.firstname < b.firstname) { return -1; } if(a.firstname > b.firstname) { return 1; } return 0; })
This code is going to work with any type.
Note that in "real life"™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc when you compare strings, so you may want to use localeCompare
. See other answers for clarity.
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