How to Sort an Array of Objects by Property in JavaScript
Table of Contents
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.
JAVASCRIPTconst 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.
JAVASCRIPTarray.sort((a, b) => a.age - b.age);
If you console.log
this array, you get this:
BASH0: {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.
JAVASCRIPTarray.sort((a, b) => a.name.localeCompare(b.name));
This is the output:
BASH0: {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:
JAVASCRIPTarray.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!
- Getting Started with TypeScript
- Getting Started with Svelte
- Getting Started with Express
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js