How to Sort an Array of Objects by Property in JavaScript

Updated onbyAlan Morel
How to Sort an Array of Objects by Property in JavaScript

When you have an array of objects, it is more involved to do things like sorting and filtering because you have to dive into each object to get the value you want.

In this post, we're going to learn how you can sort an array of objects by a specific property.

Sort an Array of Objects by Property Value

Let's start by initializing an array of objects.

JAVASCRIPT
const array = [ { name: "John", age: 30 }, { name: "Jane", age: 34 }, { name: "Joe", age: 20 } ];

Each element in this array is an object literal containing a string for the name and an integer for the age.

Let's say you wanted these people in order of age, from youngest to oldest.

For this, we can use the sort method on the array. This method takes a function as a parameter, and sorts the array based on the function.

If the function returns -1, then the first element is less than the second element and therefore should be placed before the second element.

JAVASCRIPT
array.sort((a, b) => a.age - b.age);

If you console.log this array, you get this:

BASH
0: {name: 'Joe', age: 20} 1: {name: 'John', age: 30} 2: {name: 'Jane', age: 34}

This also works for sorting strings. In this case,instead of comparing the age, we're comparing the name.

JAVASCRIPT
array.sort((a, b) => a.name.localeCompare(b.name));

This is the output:

BASH
0: {name: 'Jane', age: 34} 1: {name: 'Joe', age: 20} 2: {name: 'John', age: 30}

The objects were sorted by the name in alphabetical order.

You can even combine the sorting by making a more complex sorting function:

JAVASCRIPT
array.sort((a, b) => { if (a.age > b.age) { return 1; } else if (a.age < b.age) { return -1; } else { return a.name.localeCompare(b.name); } });

This function sorts them by age, but if the ages are the same, it sorts them by name, giving you fine grain control over the sort order.

Conclusion

In this post, we learned how to sort an array of objects by a specific property.

Simply take advantage of the built-in sort method on arrays and you can sort an array of objects by any property by just comparing them.

Hopefully, you've found this useful to you. Happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.