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

103
Vistas
Change array list into multiple array lists every 3 items

I want to filter a large array list into multiple arrays for every 5 items in a certain way so that [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] would be [[1, 2, [3, 4, 5]], [6, 7, [8, 9, 10]]] or [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] would be [[1, 2, [3, 4, 5]], [6, 7, [8, 9, 10]], [11, 12, [13, 14, 15]]]. (All arrays will be a multiple of 5 in my program.)

How would I do this?

Right now I'm doing this

for (var i = 1; i < (stoneTextureUnfiltered.length+1)/1.01; i++) {
    stoneTexture.push([stoneTextureUnfiltered[i], stoneTextureUnfiltered[i+1], stoneTextureUnfiltered[i+2], [stoneTextureUnfiltered[i+3], stoneTextureUnfiltered[i+4], stoneTextureUnfiltered[i+5]]]);
}

but it doesn't seem to be working.

Thanks,

-Voxel

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Assuming you've chunked the array already into parts of 5 with these answers and it's stored in a variable named chunks, to wrap the last 3 in each chunk you can use map:

const final = chunks.map((chunk) => [chunk[0], chunk[1], chunk.slice(2)]);

You add the first and second elements to the new list, then add the rest of the chunk as a whole.

Demo below:

// using second answer
var perChunk = 5 // items per chunk    

var inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

var chunks = inputArray.reduce((resultArray, item, index) => { 
  const chunkIndex = Math.floor(index/perChunk)

  if(!resultArray[chunkIndex]) {
    resultArray[chunkIndex] = [] // start a new chunk
  }

  resultArray[chunkIndex].push(item)

  return resultArray
}, [])

// answer below

const final = chunks.map((chunk) => [chunk[0], chunk[1], chunk.slice(2)]);

console.log(final);

As you can see, it works nicely!

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