How to use forEach with a Separate Function In Javascript
- Define a function calculateAverage that takes an array as an argument.
- Initialize variables sum and count to keep track of the sum and count of negative numbers.
- Use arr.forEach to iterate through each element in the array.
- Within the forEach loop:
- Check if the current element is negative.
- If it is negative, add it to sum and increment count.
- Calculate the average of negative numbers as a sum/count.
- Call the calculateAverage function with the array as an argument to find the average.
Example: Below is an example to finding the average of all negative numbers in array using using forEach with a separate function.
function avg(arr) {
let sum = 0, count = 0;
arr.forEach(num => {
if (num < 0) {
sum += num;
count++;
}
});
return count > 0 ? sum / count : 0;
}
const nums = [-2, 3, -5, 7, -8, -10, 15];
console.log("Average of negative numbers:", avg(nums));
Output
Average of negative numbers (Using forEach): -6.25
Time Complexity: O(n)
Space Complexity: O(1)
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