Computer >> Computer tutorials >  >> Programming >> Javascript

Sum of all positives present in an array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers (positive and negative). Our function should calculate and return the sum of all the positive numbers present in the array.

Example

Following is the code −

const arr = [5, -5, -3, -5, -7, -8, 1, 9];
const sumPositives = (arr = []) => {
   const isPositive = num => typeof num === 'number' && num > 0;
   const res = arr.reduce((acc, val) => {
      if(isPositive(val)){
         acc += val;
      };
      return acc;
   }, 0);
   return res;
};
console.log(sumPositives(arr));

Output

Following is the console output −

15