简体   繁体   中英

how to find total sum of nested array in javascript

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM