Sum of all positives present in an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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
raja
Published on 17-Apr-2021 11:53:41
Advertisements