在 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中文網其他相關文章!