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 Svelte
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor