Home >Web Front-end >JS Tutorial >How to Sort a Multi-Field Array in JavaScript?

How to Sort a Multi-Field Array in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-24 02:18:10530browse

How to Sort a Multi-Field Array in JavaScript?

Multi-field Array Sorting

In an earlier question, we explored array sorting based on a single field. However, real-world scenarios often require sorting on multiple criteria. This article demonstrates how to adapt that approach for multi-field sorting.

Specific Example: City and Price

Consider the following Homes array where we need to sort by city (ascending) and then price (descending):

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" }
];

Multi-field Sorting Approach

To sort based on multiple fields, we can use a chained sorting approach that involves comparing the values of the selected fields, one at a time, until we find a difference.

Implementation

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

Explanation

  • The localeCompare method is used to compare the city values.
  • If the city values are equal, we subtract the price value of b from a to sort the prices in descending order.
  • The resulting array is sorted by city (ascending) and then price (descending).

Output

[
  {
    "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"
  }
]

This approach provides a flexible solution for sorting arrays on multiple fields. It can be easily modified to accommodate any number of sorting criteria, making it suitable for a wide variety of data manipulation scenarios.

The above is the detailed content of How to Sort a Multi-Field Array 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