Home > Software design >  how to find total sum of nested array in javascript
how to find total sum of nested array in javascript

Time:07-19

How to find sum of only first nested array?

let arr = [[1,2,3],[4,5,6]];

I tried using map with reduce method. but it is returning both nested array's sum individually.

arr.map((value, i) => value.reduce((acc, curr) => acc   curr,0));

output- [6,15]

But i want only first nested array sum.

so it should be [[6],[4,5,6]];

CodePudding user response:

I Think This Should Work:

let arr = [
  [1, 2, 3],
  [4, 5, 6],
];

let newArray = arr.map((value, i) => {
  if (i === 0) {
    return [value.reduce((acc, curr) => acc   curr, 0)];
  } else {
    return value;
  }
});

console.log(newArray);

Output:

[[6],[4,5,6]];

CodePudding user response:

You only need to modify first index why iterate over all the values using map reduce?

arr = [
  [1, 2, 3],
  [4, 5, 6],
]

arr[0] = [arr[0].reduce((acc, curr) => acc   curr, 0)]

arr will return [[6],[4,5,6]]
  • Related