
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- Sum of distinct elements of an array - JavaScript
- Compute cartesian product of elements in an array in JavaScript
- Replace a value if null or undefined in JavaScript?
- Sum of distinct elements of an array in JavaScript
- JavaScript reduce sum array with undefined values
- Sum of all the non-repeating elements of an array JavaScript
- How to find the biggest number in an array around undefined elements? - JavaScript
- How to check for null, undefined, or blank variables in JavaScript?
- Absolute sum of array elements - JavaScript
- Thrice sum of elements of array - JavaScript
- Finding desired sum of elements in an array in JavaScript
- How to remove blank (undefined) elements from JavaScript array - JavaScript
- Compute sum of all elements in 2 D array in C
- How to check for 'undefined' or 'null' in a JavaScript array and display only non-null values?
- Pair of (adjacent) elements of an array whose sum is lowest JavaScript

Advertisements