Search code examples
javascriptreactjssorting

Sort an array of objects in React and render them


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?


Solution

  • 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.