Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - how to start forEach loop at some index

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]);
}
like image 449
Leff Avatar asked Sep 02 '25 04:09

Leff


2 Answers

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.

like image 185
Nina Scholz Avatar answered Sep 04 '25 20:09

Nina Scholz


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;
})
like image 38
kind user Avatar answered Sep 04 '25 20:09

kind user