Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

623
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.

9 months 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(','));
9 months 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

9 months ago · Santiago Trujillo Denunciar

0

Take a look at this. array.slice()

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

9 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos