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

132
Visualizações
Why is reduce index 1-based sometimes?

I've just come across an annoying bug (in my code) that was caused by the JavaScript Array.reduce method.

I've created a minimal reproduction of the issue below.

const people = [{name: 'bob'}, {name: 'fred'}, {name: 'john'}]

people.reduce((acc, person, i) => {
  if (i === 0) throw Error('this error is never thrown')
  if (i === 1) console.log(acc === people[0])
  console.log(i, person.name)
  return acc
})

people.reduce((acc, person, i) => {
  if (i === 0) console.log(acc === null)
  console.log(i, person.name)
  return acc
}, null)

Why does the first piece of code above iterate twice only whilst the second use of reduce iterates three times (once for each array item) as expected?

Are there any docs documenting this behaviour or is this a bug in Chrome? If its not a bug, why does this behaviour exist? TIA

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

0

reduce() has the second param (optional) as initial value of the aggregation. From the docs:

If initialValue is not specified, previousValue is initialized to the first value in the array, and currentValue is initialized to the second value in the array.

In your code bob is skipped and so is its index. So this is the correct behaviour

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