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

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

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