I have an array with alot of items, and I am creating a list of them. I was thinking of paginating the list. I wonder how can I start a forEach
or for
loop at some index
in an array, that would be in my example the number of items in the list on each page, so that I don't need to iterate over the whole array in each loop?
arr.forEach(function (item) {
someFn(item);
})
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
You could use a copy of the array, by using Array#slice
The
slice()
method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
array.slice(10, 20).forEach(someFn); // only for functions which respects API of forEach*
* parameters for a callback
Or you can start at a given index and end at a given index.
for (var i = 10, len = Math.min(20, arr.length); i < len; i++) {
someFn(arr[i]);
}
With
Math.min(20, arr.length)
returns a value, if the array is smaller than the given value 20
. For example if the array has only index 0 ... 14, you get as result 15.
Unfortunately Array#forEach
iterates over every element in the given array, but you could apply a simple condition to determine to which elements (with specified index) apply the given function.
i > 3 ? someFn(item) : null;
^ if index more than 3 - call the function
var arr = [1,2,3,4,5,6,7];
function someFn(elem){
console.log(elem);
}
arr.forEach(function(item, i) {
return i > 3 ? someFn(item) : null;
})
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