使用JavaScript 進行陣列排序:按屬性值排序
許多程式設計任務涉及使用物件陣列,通常需要將它們排序特定的方式。排序在組織資料和從資料中提取有意義的見解方面發揮著至關重要的作用。在本例中,我們的目標是根據物件的「價格」屬性對物件陣列進行升序和降序排序。
下面的 JavaScript 程式碼提供了此任務的解決方案:
// Array of objects representing homes var homes = [ { "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500" }, { "h_id": "4", "city": "Bevery Hills", "state": "CA", "zip": "90210", "price": "319250" }, { "h_id": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500" } ]; // Function to sort the array of homes by price in ascending order function sortByPriceAsc(a, b) { return parseFloat(a.price) - parseFloat(b.price); } // Function to sort the array of homes by price in descending order function sortByPriceDesc(a, b) { return parseFloat(b.price) - parseFloat(a.price); } // Sort homes by price in ascending order homes.sort(sortByPriceAsc); // Or after ES6 version: homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price)); // Sort homes by price in descending order homes.sort(sortByPriceDesc); // Or after ES6 version: homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
以上是如何在 JavaScript 中依特定屬性值對物件陣列進行排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!