Compute the Sum of Elements of an Array in JavaScript



Let’s say, we have an array of arrays, each containing some numbers along with some undefined and null values. We are required to create a new array that contains the sum of each corresponding sub array elements as its element. And the values undefined and null should be computed as 0.

Following is the sample array −

const arr = [[
   12, 56, undefined, 5
], [
   undefined, 87, 2, null
], [
   3, 6, 32, 1
], [
   undefined, null
]];

The full code for this problem will be −

Example

const arr = [[
   12, 56, undefined, 5
   ], [
      undefined, 87, 2, null
   ], [
      3, 6, 32, 1
   ], [
      undefined, null
]];
const newArr = [];
arr.forEach((sub, index) => {
   newArr[index] = sub.reduce((acc, val) => (acc || 0) + (val || 0));
});
console.log(newArr);

Output

The output in the console will be −

[ 73, 89, 42, 0 ]
Updated on: 2020-08-19T07:17:58+05:30

731 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements