![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 ]
Advertisements