

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compute the sum of elements of an array which can be null or undefined 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 ]
- Related Questions & Answers
- Sum of distinct elements of an array - JavaScript
- Sum of distinct elements of an array in JavaScript
- Compute cartesian product of elements in an array in JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Find the sums for which an array can be divided into subarrays of equal sum in Python
- Replace a value if null or undefined in JavaScript?
- Thrice sum of elements of array - JavaScript
- Absolute sum of array elements - JavaScript
- JavaScript reduce sum array with undefined values
- Check if the elements of the array can be rearranged to form a sequence of numbers or not in JavaScript
- Finding desired sum of elements in an array in JavaScript
- Finding sum of alternative elements of the array in JavaScript
- Compute sum of all elements in 2 D array in C
- Pair of (adjacent) elements of an array whose sum is lowest JavaScript
- How to find the biggest number in an array around undefined elements? - JavaScript
Advertisements