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

75
Visualizações
4th argument in reduce

Here is the function:

 function chunk(array: number[], size: number): number[][] {
    return array.reduce((chunks, curr, _, arr) => {
        console.log(arr.length); // -> 10 which is correct

        // let len = arr.length; // -> Cannot read properties of undefined (reading 'length')

        let len = chunks.length; // this works
        if (len === 0 || chunks[len - 1].length === size) chunks.push([curr]);
        else chunks[len - 1].push(curr);
        return chunks;
    }, []);
}

    console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)); // ->[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]

The fourth argument to reduce is the array that we're iterating over. I can log it and I get the correct result (10) see above. But when I try to use it and assign it to a variable I get an error(see above). Could someone please shed some light?

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

0

From Mozilla's page, the fourth parameter is the array that is being reduced. You should access the array variable that is already declared, but the fourth parameter works.

For example:

array.reduce((_, __, ___, arr) => {
  console.log(arr.length == array.length) // true, this is the source array
});

The reason why you're getting the error is not because of the arr.length property, but rather the way you're accessing chunks.

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