Home > database >  JS Reduce: sum specific position in a nested array of numbers
JS Reduce: sum specific position in a nested array of numbers

Time:11-02

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?

CodePudding user response:

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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related