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
Release: 2024-12-24 02:18:10
Original
555 people have browsed it

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

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;
});
Copy after login

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"
  }
]
Copy after login

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 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template