Questions:
You get an array of numbers, return the sum of all of the positives ones.
Example [1,-4,7,12]
=> 1 + 7 + 12 = 20
Note: array may be empty, in this case return 0
.
Solutions:
A
function positiveSum(arr) { var total = 0; arr.forEach(function(a) { if(a>0) { total += a; } }); return total; }
B
function positiveSum(arr) { return arr.filter(function(a){ return a > 0; }).reduce(function(total, num) { return total + num; }, 0); }
This question is referred from Codewars