Sorting Arrays of Objects in JavaScript by Key

Sorting an Array by a Specific Key

Sorting an array of objects by a specific key in JavaScript is a common task. The primary method used is the sort method available on arrays. Here's how you can do it:

Using the sort method:

To sort an array of objects by a specific key, you pass a comparator function to the sort method. This function compares two objects and determines their order in the sorted array.


const arr = [
  { id: 3, name: 'David' },
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Charlie' }
  ];
arr.sort((a, b) => a.id - b.id);
console.log(arr);
// Output:
// [
//   { id: 1, name: 'Alice' },
//   { id: 2, name: 'Charlie' },
//   { id: 3, name: 'David' }
// ]

In the example above, we're sorting by the id key. The comparator function is (a, b) => a.id - b.id, which sorts in ascending order based on the id. If you wanted to sort in descending order, you would switch a and b in the subtraction.

Using a Generic Function to Sort by Any Key

If you find yourself frequently needing to sort arrays of objects by various keys, it might be useful to create a more generic function.


function sortByKey(array, key) {
  return array.sort((a, b) => {
    if (a[key] < b[key]) return -1;
    if (a[key] > b[key]) return 1;
    return 0;
  });
}
const arr = [
  { id: 3, name: 'David' },
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Charlie' }
]
const sortedArr = sortByKey(arr, 'name');
console.log(sortedArr);
// Output:
// [
//   { id: 1, name: 'Alice' },
//   { id: 2, name: 'Charlie' },
//   { id: 3, name: 'David' }
// ]

In this example, the sortByKey function can sort an array of objects by any specified key.

Sorting an Array by Multiple Keys

In JavaScript, if you want to sort an array of objects by multiple keys, you can use the `sort()` function in combination with a comparator function. Here's a general approach:

1. Use the `sort()` method on the array.

2. In the comparator function, compare the values of the first key.

3. If the values of the first key are equal, compare the values of the next key, and so on.

Here's an example:

Imagine you have the following array of objects, and you want to sort them first by `age` and then by `name`:


const users = [
{ name: 'John', age: 25 },
{ name: 'Doe', age: 25 },
{ name: 'Anna', age: 22 },
{ name: 'Chris', age: 22 },
{ name: 'Mike', age: 30 }
];
users.sort((a, b) => {
if (a.age !== b.age) {
return a.age - b.age; // Sort by age first
} else {
return a.name.localeCompare(b.name); // If ages are the same, sort by name
}
});
console.log(users);

This will output:


[
{ name: 'Anna', age: 22 },
{ name: 'Chris', age: 22 },
{ name: 'Doe', age: 25 },
{ name: 'John', age: 25 },
{ name: 'Mike', age: 30 }
]

Notice how users with the same age are sorted by their name. You can extend this approach to include more keys if needed.