Categories
React Answers

How to sort an array of objects in React and render them?

Spread the love

Sometimes, we want to sort an array of objects in React and render them.

In this article, we’ll look at how to sort an array of objects in React and render them.

How to sort an array of objects in React and render them?

To sort an array of objects in React and render them, we call sort before we call map.

For instance, we write

const sorted = [...data]
  .sort((a, b) => a.timeM - b.timeM)
  .map((item, i) => (
    <div key={i}>
      {item.matchID}
      {item.timeM} {item.description}
    </div>
  ));

to call sort with a callback that sorts by the timeM value of each object in data in ascending order.

Then we call map with a callback that returns the rendered items.

Conclusion

To sort an array of objects in React and render them, we call sort before we call map.

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 *