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.