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

104
Views
JS Reduce: sum specific position in a nested array of numbers

I want to reduce only a specific position in a nested number array

const array1 = [[1,2,3],[4,5,6],[7,8,9],[11,12,13]];

console.log(array1.reduce((prev, curr) => prev[2] + curr[2]));

The result is NaN, another solution?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

1) You should use prev not prev[2] as

prev is of type number that you are returning not an array

2) If you are adding the number then it is better to take initial value as 0 as a second argument to the reduce method.

If you won't pass second argument, then reduce will take the array element at 0 index as the starting value i.e [1, 2, 3] and then if you add [1, 2, 3] + curr[2] then it will produce value as 1,2,36, which you are not expecting

const array1 = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
  [11, 12, 13],
];

console.log(array1.reduce((prev, curr) => prev + curr[2], 0));

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!