close

[Solved] Sort an array of objects in React and render them

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Sort an array of objects in React and render them in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Sort an array of objects in React and render them Error Occurs?

Today I get the following error Sort an array of objects in React and render them in javascript.

How To Solve Sort an array of objects in React and render them Error ?

  1. How To Solve Sort an array of objects in React and render them Error ?

    To Solve Sort an array of objects in React and render them Error this.state.data.sort((a, b) => a.item.timeM > b.item.timeM).map( (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div> )

  2. Sort an array of objects in React and render them

    To Solve Sort an array of objects in React and render them Error this.state.data.sort((a, b) => a.item.timeM > b.item.timeM).map( (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div> )

Solution 1

You will need to sort your object before mapping over them. And it can be done easily with a sort() function with a custom comparator definition like

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

Solution 2

this.state.data.sort((a, b) => a.item.timeM > b.item.timeM).map(
    (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment