Categories
React Answers

How to Sort an Array of Objects in React and Then Render Them?

Spread the love

Sometimes, we want to sort objects that we want to render from an array in a React component before rendering them.

In this article, we’ll look at how to sort objects that we want to render from an array in a React component before rendering them.

Sort an Array of Objects in React and Render Them

We can sort an array of objects with the sort method.

Then we can call map to render the sorted entries.

For instance, in the render method or function component, we may write:

const myData = this.state.data
  .sort((a, b) => a.name > b.name ? 1 : -1)
  .map((item) => (
     <div key={item.id}> {item.name}</div>
  ));

We call the sort method sort the data by the name property.

We check if a.name > b.name is true .

Strings can be compared directly.

Conclusion

We can sort an array of objects with the sort method.

Then we can call map to render the sorted entries.

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 *