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?
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.
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.
forEach Asynchronous? It is not asynchronous. It is blocking.
You could use Array#slice
with negative value for the last items.
array.slice(-5).forEach()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With