Home > katas > Sum of positive (8kyu) [JavaScript]

Sum of positive (8kyu) [JavaScript]


Chek kata on Codewars

Description:

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: if there is nothing to sum, the sum is default to 0.

Solution 1

Let's use reduce() method to solve this task. It executes a reducer function (that you provide) on each element of the array, resulting in single output value. It is almost a textbook example for reducer.

function positiveSum(arr) {
  const reducer = (accumulator, current) => accumulator + (current > 0 ? current : 0)
  return arr.reduce(reducer, 0)
}

There are a few variations of this solution. The main difference is how we check if the number is positive or not.

Solution 1.1

const positiveSum = arr => arr.reduce((accumulator, current) => current > 0 ? accumulator + current : accumulator, 0);

Solution 1.2

const positiveSum = arr => arr.filter(number => number > 0).reduce((accumulator, current) => accumulator + current, 0)

Solution 1.3

const positiveSum = arr => arr.reduce((accumulator, current) => accumulator + Math.max(current, 0), 0)

Solution 2

For loop will do the trick as well.

function positiveSum(arr) {
    let sum = 0;
    for(let i = 0; i < arr.length; i++) {
        if(arr[i] > 0) sum += arr[i]
    }
    return sum
}

Solution 2.1

Or forEach loop also works fine.

function positiveSum(arr) {
  let sum = 0
  arr.forEach(num => num > 0 && (sum += num))
  return sum
}
© 2021, Andrew Losseff