Sometimes, we want to sort an array of objects with JavaScript.
In this article, we’ll look at how to sort an array of objects with JavaScript.
How to sort an array of objects with JavaScript?
To sort an array of objects with JavaScript, we call the array sort
method.
For instance, we write
const library = [
{ name: "Steve", course: "WAP", courseID: "cs452" },
{ name: "Rakesh", course: "WAA", courseID: "cs545" },
{ name: "Asad", course: "SWE", courseID: "cs542" },
];
const sortedByNname = library.sort((a, b) => a.name > b.name);
to call library.sort
with a function that compares the name
values of each entry alphabetically.
It returns an array sorted by the name
property value of each object.
Conclusion
To sort an array of objects with JavaScript, we call the array sort
method.