Skip receiving methods with javascript arrays

Are there methods with which I can skip a certain number of objects and take a certain number of objects from an array in javascript?

Basically, the template I'm looking for is this.

Let's say I have an array of 8 objects.

First cycle:

Returns objects with an index from 0 to 3 from an array.

Second cycle:

returns objects with an index of 4-7 from an array.

Third cycle :

Go back to the beginning to return objects from 0 to 3 again.

Ad infinitum .....

I would like to see a jquery-based solution, if possible, but I'm all open to raw javascript implementations, as I really want to learn.

Greetings.

+8
javascript jquery
source share
4 answers

Something like this (plain javascript, no jQuery needed;)):

var iterator = function(a, n) { var current = 0, l = a.length; return function() { end = current + n; var part = a.slice(current,end); current = end < l ? end : 0; return part; }; }; 

Then you can call it:

 var next = iterator(arr, 3); next(); // gives the first three next(); // gives the next three. //etc. 

Demo

In this form, the last iteration can return fewer elements. You can also expand it and force the function to take a variable step and another initial parameter.

If you want to wrap around, for example, if there are only two elements left to take elements from the very beginning, then it becomes a little more complicated;)

Update: The wrap will be something like this:

 var iterator = function(a, n) { var current = 0, l = a.length; return function() { end = current + n; var part = a.slice(current,end); if(end > l) { end = end % l; part = part.concat(a.slice(0, end)); } current = end; return part; }; }; 

Demo

+11
source share

I think you want Array.slice or Array.splice .

 var ary = [0,1,2,3,4,5,6,7]; alert(ary.splice(0,3).join(',')); 
+8
source share

Take a look at this. array.slice ()

http://www.w3schools.com/jsref/jsref_slice_array.asp

+1
source share

If you have a jQuery reference, jQuery has a slice> method .

0
source share

All Articles