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 1:
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.
Solution 2:
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 3:
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 4:
Try lodash sortBy
import * as _ from "lodash";
_.sortBy(data.applications,"id").map(application => (
console.log("application")
)
)
Read more : lodash.sortBy
Solution 5:
const list = [
{ qty: 10, size: 'XXL' },
{ qty: 2, size: 'XL' },
{ qty: 8, size: 'M' }
]
list.sort((a, b) => (a.qty > b.qty) ? 1 : -1)
console.log(list)
Out Put :
[
{
"qty": 2,
"size": "XL"
},
{
"qty": 8,
"size": "M"
},
{
"qty": 10,
"size": "XXL"
}
]