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: "user@domain.example",
firstname: "Anna",
id: 318,
lastAvatar: null,
lastMessage: null,
lastname: "Nickson",
nickname: "anny"
};
Suppose you have an array
users. You may useusers.sortand pass a function that takes two arguments and compare them (comparator)It should return
In our case if two elements are
aandbwe want to comparea.firstnameandb.firstnameExample:
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.