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

146
Vistas
Can't seem to identify the issue (splitting an array in chunks)

So this function is supposed to split the array into chunks the size of the second argument, e.g. [1, 2, 3, 4] with the second argument 2 would return [[1, 2], [3, 4]], if the number is 3 it would return [[1, 2, 3], [4]] and so on. My function seems to be behaving in a similar way but it only returns the first chunk, and the subsequent chunks are just empty arrays. I increase the index by by the second argument after each iteration, so I'm not sure why it's not working. Can someone please explain what exactly is happening here and where is the error in the logic?

let arr = [1, 2, 3, 4, 5, 6]

function test(arr, num) {
    let idx = 0;
    let newArr = []
    while (idx < arr.length) {
      newArr.push(arr.slice(idx, num))
      idx = idx + num
    }
    return newArr
}

console.log(test(arr, 2))

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

0

You need an index as second parameter of Array#slice, instead of the length of slice.

For example if you take the second array, index = 2 and the second parameter has to be 4, the index of the end for slicing.

                     chunks
values   1 2 3 4 5 6
indices  0 1 2 3 4 5
slice    0 2           1 2
             2 4       3 4
                 4 6   5 6   

function test(arr, num) {
    let idx = 0;
    let newArr = [];
    while (idx < arr.length) {
        newArr.push(arr.slice(idx, idx += num));
    }
    return newArr;
}

let arr = [1, 2, 3, 4, 5, 6];

console.log(test(arr, 2));

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