Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit items in a .map loop

Tags:

javascript

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;
like image 728
Sydney Loteria Avatar asked Feb 21 '17 18:02

Sydney Loteria


People also ask

How do you set a limit on a map?

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.

Is map better than for loop?

map generates a map object, for loop does not return anything. syntax of map and for loop are completely different. for loop is for executing the same block of code for a fixed number of times, the map also does that but in a single line of code.

Does map use for loop?

map does exactly the same thing as what the for loop does, except that map creates a new array with the result of calling a provided function on every element in the calling array.


3 Answers

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.

like image 89
Nina Scholz Avatar answered Oct 09 '22 23:10

Nina Scholz


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
like image 3
Seid Akhmed Agitaev Avatar answered Oct 09 '22 23:10

Seid Akhmed Agitaev


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;
like image 12
hozefam Avatar answered Oct 09 '22 23:10

hozefam