Are there methods by which I can skip a particular number of objects and take a certain number of objects from an array in javascript?
Basically the pattern I’m looking for is this.
Say I have an array of 8 objects.
First loop:
Return objects at index 0 to 3 from the array.
Second loop:
return objects at index 4 to 7 from the array.
Third loop:
Back to the beginning so return objects at 0 to 3 again.
Ad infinitum…..
I’d love to see a jquery based solution if possible but I’m all open for raw javascript implementations too as I’m eager to learn.
Cheers.
Something like this (plain JavaScript, no need for jQuery ;)):
Then you can call it:
DEMO
It this form, the last iteration might return less elements. You could also extend it and make the function accept a variable step and a different start parameter.
If you want to wrap around, like if there are only two elements left, to take elements from the beginning, then it gets a bit more sophisticated 😉
Update: Wrap around would be something like this:
DEMO