Home > Web Front-end > JS Tutorial > How can I sort an array of objects using multiple fields in JavaScript?

How can I sort an array of objects using multiple fields in JavaScript?

DDD
Release: 2024-12-25 18:37:10
Original
685 people have browsed it

How can I sort an array of objects using multiple fields in JavaScript?

Multi-Field Sorting of Object Arrays

In cases where sorting is required based on multiple fields within an array of objects, a chained sorting approach can be employed. This method involves comparing the values of each field in sequence, until a non-zero difference is obtained.

Implementation

Consider the following array of objects:

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":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":"556699"},
    {"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":"962500"}
];
Copy after login

To sort this array based on city (ascending) and then price (descending), use the following sort function:

data.sort(function (a, b) {
    return a.city.localeCompare(b.city) || b.price - a.price;
});
Copy after login

Explanation

The sort function takes a callback as an argument, which compares two objects a and b. It returns a value that determines the order of the elements:

  • If a.city.localeCompare(b.city) is less than zero, a is placed before b.
  • If a.city.localeCompare(b.city) is greater than zero, b is placed before a.
  • If a.city.localeCompare(b.city) is equal to zero, b.price - a.price is used to compare prices. A positive value places b before a, and a negative value places a before b.

Example Output

After sorting, the homes array is rearranged as follows:

[{
    "h_id": "3",
    "city": "Dallas",
    "state": "TX",
    "zip": "75201",
    "price": "162500"
},
{
    "h_id": "6",
    "city": "Dallas",
    "state": "TX",
    "zip": "75000",
    "price": "556699"
},
{
    "h_id": "4",
    "city": "Bevery Hills",
    "state": "CA",
    "zip": "90210",
    "price": "319250"
},
{
    "h_id": "5",
    "city": "New York",
    "state": "NY",
    "zip": "00010",
    "price": "962500"
}]
Copy after login

The above is the detailed content of How can I sort an array of objects using multiple fields in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template