Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

869
Views
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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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(','));
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

Take a look at this. array.slice()

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!