Sort an array of objects in React and render them
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.
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>))