Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!