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

187
Visualizações
How Reduce function really work in JavaScript?

I'm trying to use reduce function in order to find the max length array in arrays so I tried this approach at first but it didn't work

const arrays = [[1],[3,3,4],[3,4],[4,5],[6]]
let maxLength = arrays.reduce( (acc, cur) => {
    return acc.length > cur.length ? acc.length : cur.length
})

console.log(maxLength) // output : 1

so I tried to get the length in another way and it worked

const arrays = [[1],[3,3,4],[3,4],[4,5],[6]]
let maxLength = arrays.reduce( (acc, cur) => {
    return acc.length > cur.length ? acc : cur
}).length

console.log(maxLength) // output : 3

Can someone Explain what is the difference between the two approaches ?

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

0

If you're interested in the length of the longest array, store the length in the accumulator (as in the first example); if you're interested in the array with the longest length, store the array in the accumulator (as in the second example). What you can't do is mix and match.

Get the length of the longest array

In this case, you need to provide an initial value (e.g. 0) to reduce().

const arrays = [[1],[3,3,4],[3,4],[4,5],[6]];

const max = arrays.reduce((a, {length}) => Math.max(a, length), 0);

console.log(max);

Get array with the longest length

In this case, you don't need to provide an initial value as it defaults to the first element of the array.

const arrays = [[1],[3,3,4],[3,4],[4,5],[6]];

const max = arrays.reduce((a, v) => v.length > a.length ? v : a);

console.log(max);

about 4 years ago · Juan Pablo Isaza Relatório

0

In the first code, the reduce function is returning a number, while in the second, it is returning an array. When you're returning a number, the next time your function is called, it takes the length of a number, not an array. The second code is correct, because you're taking the length of an array every time.

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