Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

skip take methods with javascript arrays

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.

like image 310
James South Avatar asked Mar 28 '11 18:03

James South


2 Answers

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(','));
like image 119
Brad Christie Avatar answered Sep 27 '22 21:09

Brad Christie


Something like this (plain JavaScript, no need for jQuery ;)):

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

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:

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

like image 35
Felix Kling Avatar answered Sep 27 '22 21:09

Felix Kling