How can I JavaScript sort alphabetically by firstname in an array of objects?

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