Home >Web Front-end >JS Tutorial >How Can I Sort an Array of Objects by a Specific Property Value in JavaScript?

How Can I Sort an Array of Objects by a Specific Property Value in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-05 07:05:44208browse

How Can I Sort an Array of Objects by a Specific Property Value in JavaScript?

Array Sorting with JavaScript: Sorting by Property Values

Many programming tasks involve working with arrays of objects, often requiring them to be sorted in particular ways. Sorting plays a crucial role in organizing and extracting meaningful insights from data. In this instance, we aim to sort an array of objects based on their 'price' property, both in ascending and descending order.

The JavaScript code below provides a solution to this task:

// 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));

The above is the detailed content of How Can I Sort an Array of Objects by a Specific Property Value in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn