Javascript program to return the sum of all of the positive numbers in an array.


Example [1,-4,7,12] => 1 + 7 + 12 = 20   
           
             

Note: if there is nothing to sum or array is empty or all values are negative, the sum should default to 0.


Q: write a function named positveSum() that takes any array and returns the sum of all the positive values in that array?

Solution:



function positiveSum(arr) {
  var total = 0;    
  for (i = 0; i < arr.length; i++) {    // setup loop to go through array of given length
    if (arr[i] > 0) {                   // if arr[i] is greater than zero
      total += arr[i];                  // add arr[i] to total
    }
  }
  return total;                         // return total
}

positiveSum([1,2,-3]) //3
positiveSum([])       //0



same solution using es6:

function positiveSum(arr) {
   return arr.reduce((a,b)=> a + (b > 0 ? b : 0),0);

}

or:

function positiveSum (arr) {
  return arr.filter(x => x>=0).reduce((a, c) => a + c, 0);

}

or:

const positiveSum = (arr) => arr.reduce((sum, n) => n > 0 ? sum + n : sum, 0);

or:

function positiveSum(arr) {
  var sum = 0;
  arr.forEach(function(v,i,a) {
    if(v>0){sum+=v;}
  });
  return sum;

}


learn about javascript higher order functions and arrays to dive deep to solve more problems related to arrays. you can find more about higher order functions here. 








Post a Comment

Previous Post Next Post