Constrain Elements in a .map Loop

I would like to ask how can I limit my .map loop to 5 elements, for example, only because currently, when I access the api, it returns 20 elements. but I want to show only 5. Basically, what I found is just a loop through the entire array of objects, and not limiting it to the number of elements.

Note. I have no control over the API because I just use moviedb api

Here is my code:

var film = this.props.data.map((item) => { return <FilmItem key={item.id} film={item} /> }); return film; 
+6
source share
1 answer

You can use Array#slice and use 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 no longer use the original array, you can mutate the array with a given length of up to 5 and then iterate.

+17
source

Source: https://habr.com/ru/post/1015154/


All Articles