React array sorting and rendering

I have an array of objects containing some information. I cannot make them in the order I want, and I need help. I do them as follows:

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

Is it possible to sort them in ascending order using item.timeMthis map()function or do I need to sort them before using the map?

+27
source share
4 answers

This may be what you are 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)
    .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 . Therefore, I create a new array using the method concat.

+60
source

. sort() ,

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>))
+9
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>
)
+4
source

Try lodash sortBy

import * as _ from "lodash";
_.sortBy(data.applications,"id").map(application => (
    console.log("application")
    )
)

Read more: lodash.sortBy

0
source

Source: https://habr.com/ru/post/1675445/


All Articles