Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 471
KimR Avatar asked Apr 23 '17 14:04

KimR


People also ask

How do you sort an array of objects in Reactjs?

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.

How do you sort elements in React?

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.

How do you filter an array of objects in React?

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.


2 Answers

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.

like image 91
Mμ. Avatar answered Oct 13 '22 00:10

Mμ.


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>)) 
like image 28
Shubham Khatri Avatar answered Oct 12 '22 22:10

Shubham Khatri