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

139
Vistas
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 Respuestas
Responde la pregunta

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