sort array objects by multiple keys

How to Sort Array of Objects by Multiple Properties

JavaScript arrays and objects are powerful data structures that allow you to easily work with diverse kinds of data in a compact manner. Both arrays and JS objects offer tons of useful features and functions. Typically, web developers need to sort arrays by a single field, which can be done using sort() function, available by default in every array. But sometimes, you may need to sort array of objects by multiple properties. In this article, we will learn how to do this.


How to Sort Array of Objects by Multiple Properties

Here are the steps to sort array of objects by multiple properties. Let us say you have the following array of objects.

var data = [{ 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" }];

Let us say you want to sort the above array by city (ascending) and by price (descending). You can do this by defining a custom sorting function within sort() function as shown below.

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

The sort() function is available for every JS array. You can define your sorting criteria within this function. We have defined a function for this purpose as shown above. It take two arguments and determines which city comes first alphabetically. We use localeCompare() function for it. It saves a lot of coding and directly returns -1, 1, or 0 (for before, after or equal) as a result of comparing two strings. We also put an addition check between the price of the corresponding elements using a logical OR operator. So the sort() function will iteratively go through the array, comparing 2 elements at a time. In each iteration, a comparison is made between the city property of two objects. If the cities of two objects are the same, then their prices are also compared to decide the sort order.

In this article, we have learnt how to compare two array of JS objects by multiple keys.

Also read:

How to Get Position of Element in HTML
How to Get Duplicate Values in JS Array
How to Create Multiline Strings in JavaScript
How to Split String By Character in JS
How to Read Local Text File in Browser

Leave a Reply

Your email address will not be published.