Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  128] [ 5]  / answers: 1 / hits: 63010  / 7 Years ago, sat, april 8, 2017, 12:00:00

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]);
}

More From » arrays

 Answers
17

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.


[#58225] Wednesday, April 5, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
Sun, Dec 5, 21, 00:00, 3 Years ago
Mon, Jun 14, 21, 00:00, 3 Years ago
Mon, Jul 22, 19, 00:00, 5 Years ago
Mon, Jul 8, 19, 00:00, 5 Years ago
;