JavaScript Program to Find the average of all positive numbers in an array

In this article, we will learn how to find the average of all positive numbers in an array using JavaScript, along with examples to demonstrate the implementation.

We are given an array of integers, which may contain both negative and positive numbers. Our task is to calculate the average of all the positive numbers in the array.

Problem Description

The goal is to compute the average of all positive numbers in a given array. This involves summing up the positive numbers and dividing the sum by the count of positive numbers.

Example 1

Input: arr = [2, -5, 6, -3, 8]
Output: 5.33

Explanation: Positive numbers: 2, 6, 8
Sum = 16, Count = 3
Average = 16 / 3 = 5.33

Example 2

Input: arr = [-10, 15, 20, -7, 25]
Output: 20

Explanation: Positive numbers: 15, 20, 25
Sum = 60, Count = 3
Average = 60 / 3 = 20

Method 1: Using Basic Loop Iteration

This straightforward approach involves manually iterating through each element in the array to identify positive numbers. These numbers are then summed, and the average is calculated by dividing the sum by the count of positive numbers.

Algorithm

  • Define a function to take the array as an input parameter.
  • Initialize variables sum and count to 0 for tracking the sum and count of positive numbers.
  • Use a loop to traverse the array and check if each element is positive. If so, update the sum and count.
  • If there are no positive elements, return 0.
  • Return the sum divided by the count to get the average.
function findAverageOfPositives(arr) {
    let sum = 0;
    let count = 0;

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

    if (count === 0) {
        return 0; // No positive numbers
    }

    return sum / count;
}

let arr1 = [2, -5, 6, -3, 8];
let arr2 = [-10, 15, 20, -7, 25];

console.log("Array 1 average:", findAverageOfPositives(arr1));
console.log("Array 2 average:", findAverageOfPositives(arr2));
console.log("No positives:", findAverageOfPositives([-1, -2, -3]));
Array 1 average: 5.333333333333333
Array 2 average: 20
No positives: 0

Method 2: Using Filter and Reduce Methods

This approach utilizes JavaScript's filter() and reduce() methods. The filter() method extracts all positive numbers, and the reduce() method calculates their sum. The average is then obtained by dividing the sum by the length of the filtered array.

function findAverageOfPositives(arr) {
    // Filter positive numbers
    let positives = arr.filter(num => num > 0);

    // Handle edge case of no positive numbers
    if (positives.length === 0) {
        return 0;
    }

    // Calculate sum using reduce
    let sum = positives.reduce((acc, num) => acc + num, 0);

    // Return average
    return sum / positives.length;
}

let arr1 = [2, -5, 6, -3, 8];
let arr2 = [-10, 15, 20, -7, 25];

console.log("Array 1 average:", findAverageOfPositives(arr1));
console.log("Array 2 average:", findAverageOfPositives(arr2));
console.log("Mixed array:", findAverageOfPositives([1, -1, 2, -2, 3]));
Array 1 average: 5.333333333333333
Array 2 average: 20
Mixed array: 2

Method 3: One-Line Arrow Function

For a more concise solution, we can combine filtering, reducing, and averaging into a single expression:

const avgPositive = arr => {
    const pos = arr.filter(n => n > 0);
    return pos.length ? pos.reduce((a, b) => a + b) / pos.length : 0;
};

let testArrays = [
    [2, -5, 6, -3, 8],
    [-10, 15, 20, -7, 25],
    [-1, -2, -3],
    [5, 10, 15]
];

testArrays.forEach((arr, index) => {
    console.log(`Array ${index + 1}:`, arr, "=> Average:", avgPositive(arr));
});
Array 1: [ 2, -5, 6, -3, 8 ] => Average: 5.333333333333333
Array 2: [ -10, 15, 20, -7, 25 ] => Average: 20
Array 3: [ -1, -2, -3 ] => Average: 0
Array 4: [ 5, 10, 15 ] => Average: 10

Comparison

Method Readability Performance Best For
Basic Loop High Fast (single pass) Beginners, large arrays
Filter + Reduce High Slower (two passes) Functional programming
Arrow Function Medium Slower (two passes) Concise code

Conclusion

Finding the average of positive numbers can be accomplished through multiple approaches. The basic loop method is most efficient for large datasets, while filter/reduce methods offer cleaner, more functional code. Choose based on your performance requirements and coding style preferences.

Updated on: 2026-03-15T23:19:01+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements