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

219
Visualizações
How to take every nth continuous elements from an array?

Im a bit new to javascript and my goal is to take every 3 elements in my array and store them as an array to be pushed to another array. Below is what this would look like

var a = [11, 2, 3, 4, 5, 6, 7, 8, 9, 2, 2, 3, 4, 5, 4];

Output would be

var arrays = [[11, 2, 3], [4, 5, 6], [7, 8, 9], [2, 2, 3], [4, 5, 4]]

These are just integers, but in my application, there is an array containing 73 objects which id like to store like this.

var objects = [{}, {}, {}], [{}, {}, {}] ,,,]

would there be any problems based on the number of objects as 73 is not divisible by three

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Something like this, the objects are abitrary here. I'm using .slice to get each next group of 3, and pushing it onto the buffer array. I'm using .length as my bound in the for loop and incrementing by 3 each time.

var a = [
  {x:11}, {x:2}, {x:3}, {x:4}, {x:5}, {x:6}, {x:7}, 
  {x:8}, {x:9}, {x:2}, {x:2}, {x:3}, {x:4}, {x:5}, {x:4}
];

buffer = [];
for(i=0; i<a.length; i+=3) {
  buffer.push(a.slice(i, i+3));
}
console.log(buffer);

Also, slice can handle arrays that aren't divisible by 3. You can see in this example the leftover object is in its own array.

var a = [
  {x:11}, {x:2}, {x:3}, {x:4}, {x:5}, {x:6}, {x:7}, 
  {x:8}, {x:9}, {x:2}, {x:2}, {x:3}, {x:4}, {x:5}, 
  {x:4}, {x:112}
];

buffer = [];
for(i=0; i<a.length; i+=3) {
  buffer.push(a.slice(i, i+3));
}
console.log(buffer);

You can also easily adapt to any n elements:

var a = [
  {x:11}, {x:2}, {x:3}, {x:4}, {x:5}, {x:6}, {x:7}, 
  {x:8}, {x:9}, {x:2}, {x:2}, {x:3}, {x:4}, {x:5}, 
  {x:4}, {x:112}
];

let n = 4;
buffer = [];
for(i=0; i<a.length; i+=n) {
  buffer.push(a.slice(i, i+n));
}
console.log(buffer);

Let me know if this helps.

about 4 years ago · Juan Pablo Isaza 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