Sorting an Array by First Name in JavaScript
In JavaScript, sorting an array by a specific property requires a sorting function. This code demonstrates how to sort an array by the "firstname" property in alphabetical order:
var userArray = [{ firstname: "Anna", lastname: "Nickson", email: "user@example.com" }, { firstname: "Bob", lastname: "Smith", email: "bob@example.com" }, { firstname: "Carol", lastname: "Jones", email: "carol@example.com" }]; // Sort the array by "firstname" using localeCompare userArray.sort((a, b) => a.firstname.localeCompare(b.firstname)); console.log(userArray); // Output: [{firstname: "Anna", ..., {firstname: "Bob", ..., {firstname: "Carol", ...}
Here's a breakdown of the code:
Sorting Function (a, b) => a.firstname.localeCompare(b.firstname):
The above is the detailed content of How do I sort an array of objects by first name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!