Limit items in a .map loop

Javascript

Javascript Problem Overview


I would like to ask how can I limit my .map loop for example to a 5 items only because currently when I access an api it returns 20 items. but I want to display only 5. Mostly that I found is just looping all throughout the array of objects and not limiting it to a number of items.

Note: I have no control on the API because I'm just using the moviedb api

Here's my code:

var film = this.props.data.map((item) => {
  return <FilmItem key={item.id} film={item} />
});

return film;

Javascript Solutions


Solution 1 - Javascript

You could use Array#slice and take only the elements you need.

var film = this.props.data.slice(0, 5).map((item) => {
        return <FilmItem key={item.id} film={item} />
    });

return film;

If you do not need the original array anymore, you could mutate the array by setting the length to 5 and iterate them.

Solution 2 - Javascript

You could use filter() as well

var film = this.props.data.filter((item, idx) => idx < 5).map(item => {
   return <FilmItem key={item.id} film={item} />
});

return film;

Solution 3 - Javascript

You can also limit it by passing a second argument to a map() callback, which would be an index of an item in the loop.

const film = this.props.data?.map(
  (item, index) => 
    index < 5 && ( // <= only 5 items
      <FilmItem 
        key={item.id} 
        film={item} 
      />
    )
);

return film;

However, you probably should stick to Nina's answer unless you really need some elegancy in your code. Since I'm guessing my answer would be slower performance-wise.

References:

  1. MDN: map() syntax
  2. Optional Chaining

Solution 4 - Javascript

Hi, If you are using a functional component. you can try this:

<p>const [film, setFilm] = useState([])</p>

<i>// Fetch data from API</i>

<p>useEffect(() =>{...})</p>

var fiveFilm = film.slice(0,5)

in your return function:

you can map using:

{fiveFilm.map(item => <p>{item.name}<p>)}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSydney LoteriaView Question on Stackoverflow
Solution 1 - JavascriptNina ScholzView Answer on Stackoverflow
Solution 2 - JavascripthozefamView Answer on Stackoverflow
Solution 3 - JavascriptSeid Akhmed AgitaevView Answer on Stackoverflow
Solution 4 - JavascriptANOOP NAYAKView Answer on Stackoverflow