Open In App

JavaScript Program to Find the Average of all Positive Numbers in an Array

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of size N, the task is to calculate and return the average of all positive elements of the given array. There are several ways to find the average of all the positive numbers in an array using JavaScript which are as follows:

Using for Loop

In this approach, we are using a for loop to iterate through each element of the array, checking if it’s positive, and then calculating the sum and count of positive numbers to find the average.

Syntax:

for (statement 1 ; statement 2 ; statement 3){
code here...
}

Example: The below example uses for loop to find the average of all positive numbers in an array.

JavaScript
let numbers = [3, 7, -2, 5, -8, 9];
let sum = 0;
let cnt = 0;
for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] > 0) {
        sum += numbers[i];
        cnt++;
    }
}
let res = cnt > 0 ? sum / cnt : 0;
console.log("Average:", res);

Output
Average: 6

Using reduce method

In this approach, we are using the reduce method to filter out positive numbers, then calculate their sum using reduce, and finally find the average by dividing the sum by the number of positive numbers.

Syntax: 

array.reduce( function(total, currentValue, currentIndex, arr), 
initialValue )

Example: The below example uses reduce method to find the average of all positive numbers in an array.

JavaScript
let numbers = [3, 7, -2, 5, -8, 9];
let pNum = numbers
    .filter(num => num > 0);
let sum = pNum
    .reduce((acc, cur) => acc + cur, 0);
let res = pNum
    .length > 0 ? sum / pNum.length : 0;
console.log("Average:", res);

Output
Average: 6

Using forEach Loop

In this approach, we are using the forEach loop to iterate through each element of the array, checking if it’s positive, and then calculating the sum and count of positive numbers to find the average.

Syntax:

array.forEach(callback(element, index, arr), thisValue);

Example: The below example uses forEach loop to find the average of all positive numbers in an array.

JavaScript
let numbers = [3, 7, -2, 5, -8, 9];
let sum = 0;
let cnt = 0;
numbers.forEach(num => {
    if (num > 0) {
        sum += num;
        cnt++;
    }
});
let res = cnt > 0 ? sum / cnt : 0;
console.log("Average:", res);

Output
Average: 6


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads