在 JavaScript 中按名字对数组进行排序
在 JavaScript 中,按特定属性对数组进行排序需要排序函数。此代码演示了如何按“firstname”属性按字母顺序对数组进行排序:
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", ...}
以下是代码细分:
排序函数 (a, b) => a.firstname.localeCompare(b.firstname):
以上是如何在 JavaScript 中按名字对对象数组进行排序?的详细内容。更多信息请关注PHP中文网其他相关文章!