Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map an index range in react?

<table>
   <tbody>
   {this.state.data.map((person, i) => <TableRow key = {i} data = {person} />)}
   </tbody>
</table>

This maps my entire array, but how would I map from a minimum index to a maximum index? So say my array has 500 elements. I want to map this array (of data) from index 15 to 24 inclusive. (So I'd only have 10 elements on my screen).

edit: these answers are interesting.. but no mention of .filter() though? I saw that it might help what I want but I'm trying to figure out how to do it in react.

like image 466
Shai UI Avatar asked Feb 06 '18 21:02

Shai UI


1 Answers

Use Array#slice() to extract a shallow copy of the values you want from this.state.data.

const SubsetTable = props => {
  let {startIndex, endIndex, data} = props

  let subset = data.slice(startIndex, endIndex)

  return (
   <table>
     <tbody>
       {subset.map((person, i) => (<TableRow key = {i} data = {person} />)}
     </tbody>
   </table>
  )
}

// Since splice() is inclusive of the range given, you'll need to 
// adjust your range to include that last index if needed
// The below will grab all values in indexes 15-24, 
<SubsetTable startIndex={15} endIndex={25} data={this.state.data} />

Since you've updated your question, regarding use of Array#filter(), filter() requires that you iterate over the entire set. Array#slice() is only going to extract the contiguous index range that you'd like extract. filter() is better when you gave a condition that you want all your Array data members to meet and and your collection is unordered.

like image 134
peteb Avatar answered Sep 19 '22 19:09

peteb