JavaScript reduce sum array with undefined values

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 19-Aug-2020 07:18:36
Advertisements