JavaScript – Sum of Positives

To write a JavaScript function that calculates the sum of positive numbers from an array, you can follow these approaches : first will make use of reduce & the second one will be using simple for loop.

Using reduce

const positiveSum = arr => arr.reduce((sum, num) => num > 0 ? sum + num : sum, 0);
console.log(positiveSum([1, 2, 1, 3, 5])); // 12
console.log(positiveSum([1, -2, -3, 4, 5])); // 10
console.log(positiveSum([-1, -2, -3, -4, -5])); // 0
console.log(positiveSum([])); // 0

This function iterates through the array and adds only the positive numbers to the sum. If the array is empty, the initial value of 0 is returned.

Using loop

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

console.log(positiveSum([1, 2, 1, 3, 5])); // 12
console.log(positiveSum([1, -2, -3, 4, 5])); // 10
console.log(positiveSum([-1, -2, -3, -4, -5])); // 0
console.log(positiveSum([])); // 0

This method uses simple for loop to iterate through the array and check if the number is positive before adding.

Similar Reads