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?
To sort an array of objects in React:Create a shallow copy of the array. Call the sort() method on the array passing it a function. The function is used to define the sort order.
First, in a new blank React app, we will create an array of strings which will be our list. Then we will map it out as an unordered list. We will also create the dropdown to select which type of sorting needs to be applied. import { React, useState } from "react"; import "./App.
To filter an array of objects in React:Call the filter() method on the array. On each iteration, check if a certain condition is met. The Array. filter methods returns an array with all elements that satisfy the condition.
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>))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With