JavaScript reduce sum array with undefined values


We have an array of numbers that contains some undefined and null values as well. We are required to make a function, say quickSum that takes in the array and returns its quick sum, ignoring the undefined and null values.

The full code for doing so will be −

Example

const arr = [23,566,null,90,-32,undefined,32,-69,88,null];
const quickSum = (arr) => {
   const sum = arr.reduce((acc, val) => {
      return acc + (val || 0);
   }, 0);
   return sum;
};
console.log(quickSum(arr));

Output

The output in the console will be −

698

Updated on: 19-Aug-2020

542 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements