Find Average of All Positive Numbers in an Array in JavaScript



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.

Input 1

arr = [2, -5, 6, -3, 8];

Output 1

5.33 

Explanation

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

Input 2

arr = [-10, 15, 20, -7, 25];

Output 2

20

Explanation

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

Using the Brute Force Approach

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. 

Steps for Implementation

  • 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.

Implementation Code

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;
    }

    return sum / count;
}

let arr = [2, -5, 6, -3, 8];
console.log("Average of positive numbers:", findAverageOfPositives(arr));

Output

Average of positive numbers: 5.33

Using the Filter and Reduce Approach

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.

Steps for Implementation

  • Define a function and pass the array as a parameter.
  • Use the filter() method to extract all positive numbers. 
  • Use the reduce() method to calculate the sum of positive numbers.
  • Handle cases where the array has no positive numbers by returning 0.
  • Return the average by dividing the sum by the length of the filtered array.

Implementation Code

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

    // Step 3: Calculate the sum of positive numbers
    let sum = positives.reduce((acc, num) => acc + num, 0);

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

    // Step 5: Calculate the average
    return sum / positives.length;
}

// Step 6: Test the function
let arr = [-10, 15, 20, -7, 25];
console.log("Average of positive numbers:", findAverageOfPositives(arr));

Output

Average of positive numbers: 20

Conclusion

Finding the average of positive numbers in an array can be achieved through different approaches. The brute force method involves direct iteration, while the filter and reduce method simplifies the process with built-in JavaScript functions. Choose the method that best fits your application and performance needs. 

Updated on: 2025-01-27T12:33:21+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements