Sort an array of objects in React and render them Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Sort an array of objects in React and render them without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have an array of objects containing some information. I am not able to render them in the order I want and I need some help with that. I render them like this:

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

Is it possible to sort them ascending with item.timeM in that map()-function or do I have to sort them before i use map?

Answer

This might be what you’re looking for:

// ... rest of code

// copy your state.data to a new array and sort it by itemM in ascending order
// and then map 
const myData = [].concat(this.state.data)
    .sort((a, b) => a.itemM > b.itemM ? 1 : -1)
    .map((item, i) => 
        <div key={i}> {item.matchID} {item.timeM}{item.description}</div>
    );

// render your data here...

The method sort will mutate the original array . Hence I create a new array using the concat method. The sorting on the field itemM should work on sortable entities like string and numbers.

We are here to answer your question about Sort an array of objects in React and render them - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji