Introduction
In this lab, we will learn how to sort an array of objects alphabetically based on a given property using JavaScript. We will use the Array.prototype.sort() method and the String.prototype.localeCompare() method to compare the values for the given property. This will allow us to easily sort the array in ascending or descending order, based on our requirements.
How to Sort an Array Alphabetically Based on a Given Property in JavaScript
To sort an array of objects alphabetically based on a given property in JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.sort()to sort the array based on the given property. - Use
String.prototype.localeCompare()to compare the values for the given property.
Here's an example code snippet that you can use:
const alphabetical = (arr, getter, order = "asc") =>
arr.sort(
order === "desc"
? (a, b) => getter(b).localeCompare(getter(a))
: (a, b) => getter(a).localeCompare(getter(b))
);
You can call the alphabetical function with an array of objects and the getter function that returns the property to sort by. Here's an example usage:
const people = [{ name: "John" }, { name: "Adam" }, { name: "Mary" }];
alphabetical(people, (g) => g.name);
// [ { name: 'Adam' }, { name: 'John' }, { name: 'Mary' } ]
alphabetical(people, (g) => g.name, "desc");
// [ { name: 'Mary' }, { name: 'John' }, { name: 'Adam' } ]
Summary
Congratulations! You have completed the Sort Array Alphabetically lab. You can practice more labs in LabEx to improve your skills.