Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

Take a look at this. array.slice()

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda