Functional Approach (Using Array Methods)
- Use array methods like filter to extract negative numbers.
- Use reduce to calculate the sum of these negative numbers.
- Calculate the average as a sum/count.
Example: Below is an example to finding the average of all negative numbers in array using functional approach(using array methods).
const numbers = [-2, 3, -5, 7, -8, -10, 15];
const negativeSum =
numbers.filter(num => num < 0).reduce((acc, cur) => acc + cur, 0);
// Count the number of negative numbers
const count = numbers.filter(num => num < 0).length;
// Calculate the average of negative numbers
const average = count > 0 ? negativeSum / count : 0;
// Output the average
console.log("Average of negative numbers (Functional):", average);
Output
Average of negative numbers (Functional): -6.25
Time Complexity: O(n)
Space Complexity: O(n)
JavaScript Program to Find the Average of all Negative Numbers in an Array
Given an array of numbers, the task is to find the average of all negative numbers present in the array.
Below are the approaches to find the average of all negative numbers in an array:
Table of Content
- Iterative Approach
- Functional Approach (Using Array Methods)
- Using forEach with a Separate Function
Contact Us