This post will discuss how to sort an object array by multiple properties in JavaScript.

Sorting an array of objects by multiple attributes in JavaScript is a common task that can be achieved in different ways. Here are some examples of how to sort an array of objects by multiple attributes in JavaScript given an array and a list of properties to sort by:

1. Using a comparison function

This is a common technique that works in any version of JavaScript. It involves passing a custom compare function to the Array.sort() function, which defines how to compare two elements in the array. The compare function should return a negative, zero, or positive value, depending on whether the first element is less than, equal to, or greater than the second element. To sort an array of objects by multiple attributes, we can use a loop or a chain of comparisons to compare the elements by each attribute until a non-zero value is returned. For example, if we have an array of employee objects and we want to sort it by salary in descending order, then by name in ascending order, then by age in ascending order, we can do:

Download  Run Code

Output:

[
    { name: "Oliver", salary: 50000, age: 35 },
    { name: "Benjamin", salary: 40000, age: 25 },
    { name: "Joseph", salary: 40000, age: 30 },
    { name: "Anthony", salary: 25000, age: 20 }
]

2. Using ES6 arrow function and spread operator

These are the new features of JavaScript that allows writing concise functions with a shorter syntax and expanding iterables into individual elements. It involves using an arrow (=>) to define a compare function for the sort() function and using the spread operator (…) to pass an array of attributes to sort by as arguments. We can use the same logic as the previous example, but with a simpler syntax. For example, if we want to sort the employees by salary in descending order, then by age in ascending order, we can do:

Download  Run Code

Output:

[
    { name: "Oliver", salary: 50000, age: 35 },
    { name: "Benjamin", salary: 40000, age: 25 },
    { name: "Joseph", salary: 40000, age: 30 },
    { name: "Anthony", salary: 25000, age: 20 }
]

3. Using a library

If we don’t want to write our own sorting function, we can use a library or framework that provides a built-in or custom function to sort an object array by multiple properties. For example, we can use lodash’s orderBy() function, which takes an array, an array of property names or iteratees, and an array of sorting orders as arguments. For example, to sort an array of employees by salary in descending order and then by age in ascending order, we can use this function:

Download Code

Output:

[
    { name: "Oliver", salary: 50000, age: 35 },
    { name: "Benjamin", salary: 40000, age: 25 },
    { name: "Joseph", salary: 40000, age: 30 },
    { name: "Anthony", salary: 25000, age: 20 }
]

That’s all about sorting an object array by multiple properties in JavaScript.