Categories
JavaScript Answers

How to sort an array of objects with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *