Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Is it possible to limit the results given by a forEach loop?

I have a very long JSON array that I fetch using a forEach loop where I need to display only the last 5 elements.

  array.forEach(showOnlyFiveElements => {
   //only 5 elements should be show here
  });

Can't it be done using a forEach ? Or I should go for something different?

like image 577
Folky.H Avatar asked May 02 '17 11:05

Folky.H


People also ask

Can you break out of forEach?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Can you modify array in forEach?

Note that foreach does not modify the internal array pointer, which is used by functions such as current() and key(). It is possible to customize object iteration. In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Is forEach blocking in JavaScript?

forEach Asynchronous? It is not asynchronous. It is blocking.


1 Answers

You could use Array#slice with negative value for the last items.

array.slice(-5).forEach()
like image 199
Nina Scholz Avatar answered Oct 22 '22 03:10

Nina Scholz