使用 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中文网其他相关文章!