How can I JavaScript sort alphabetically by first name in an array of objects? I have an array that includes objects like this:
var user = {
bio: null,
email: "user@domain.example",
firstname: "Anna",
id: 318,
lastAvatar: null,
lastMessage: null,
lastname: "Nickson",
nickname: "anny"
};
What’s the best way to sort this array by the firstname property?
You can directly use the sort method to compare the firstname properties of the objects. Here’s how to do it:
var users = [
{ firstname: "Anna", lastname: "Nickson" },
{ firstname: "John", lastname: "Doe" },
{ firstname: "Zara", lastname: "Ali" }
];
users.sort(function(a, b) {
return a.firstname.localeCompare(b.firstname);
});
console.log(users);
If you’re using ES6 or later, you can achieve the same result with an arrow function:
var users = [
{ firstname: "Anna", lastname: "Nickson" },
{ firstname: "John", lastname: "Doe" },
{ firstname: "Zara", lastname: "Ali" }
];
users.sort((a, b) => a.firstname.localeCompare(b.firstname));
console.log(users);
If you want to sort the array upon creation, you can use the sort method right after defining the array:
var users = [
{ firstname: "Anna", lastname: "Nickson" },
{ firstname: "John", lastname: "Doe" },
{ firstname: "Zara", lastname: "Ali" }
].sort((a, b) => a.firstname.localeCompare(b.firstname));
console.log(users);