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
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays