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

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

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