0

I am trying to figure out a way to take the first 5 items out of an array of 80 and put them into an unordered list. I am mapping the data like this but not sure how to only collect the first 5 results. <ul>{data.moves.map((item) => (<li key={index}>{item.move.name} </li>))</ul> I also tried instead of passing the entire array through the map to slice the first 5 off but I could not get that to work for me.

Any thoughts? Thanks!

Jim Amato
  • 3
  • 1
  • have you tried `data.moves.slice(0,5)` – shubham jha Oct 09 '21 at 05:51
  • 1
    Does this answer your question? [How to get first N number of elements from an array](https://stackoverflow.com/questions/34883068/how-to-get-first-n-number-of-elements-from-an-array) – jonrsharpe Oct 14 '21 at 13:25

2 Answers2

0

Like any array in JS, you can just use

arr.slice(0, 5)

to take the first 5 elements. Note that .slice() returns a new array. Docs.

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • Heh... Thought I tried that earlier but maybe I mistyped it somehow, I have been stuck on this minor problem for too long and it is starting to wear on me... But all is working great now thank you! – Jim Amato Oct 09 '21 at 05:57
0

This is a quick thing you can do:

<ul>{data.moves.map((item, idx) => (idx < 5) && (<li key={index}>{item.move.name} </li>))</ul>

That will show only the first 5 items.

  • this actually may not be recommended, if the array has 80 or 200 items. The loop will be running close to 80 or 200 times doing nothing, when it can loop it 5 times – nonopolarity Oct 09 '21 at 06:11