Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

0

Take a look at this. array.slice()

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

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda