Finding Mean at Every Point in JavaScript Array
Last Updated :
17 Jul, 2024
We have given the array of numbers and our task is to find the mean at every position in the array using JavaScript. Below we have added the example for a better understanding of the problem statement.
Example:
Input: arr = [1, 2, 3, 4, 5]
Output:
Mean at position 1: 1
Mean at position 2: 1.5
Mean at position 3: 2
Mean at position 4: 2.5
Mean at position 5: 3
Explanation:
Cumulative Sum: 1, Mean: 1/1 = 1
Cumulative Sum: 1 + 2 = 3, Mean: 3/2 = 1.5
Cumulative Sum: 1 + 2 + 3 = 6, Mean: 6/3 = 2
Cumulative Sum: 1 + 2 + 3 + 4 = 10, Mean: 10/4 = 2.5
Cumulative Sum: 1 + 2 + 3 + 4 + 5 = 15, Mean: 15/5 = 3
We can find this mean using three different methods which are stated below:
In this approach, we are using the for loop to iterate over the input array and we are calculating the mean at each position and printing the mean at each point using the console.log function.
Example: In this example, we will find the mean at every point in JavaScript using For Loop.
JavaScript
const arr = [1, 2, 3, 4, 5];
let s = 0;
for (let i = 0; i < arr.length; i++) {
s += arr[i];
const res = s / (i + 1);
console.log(`Mean at position ${i + 1}: ${res}`);
}
OutputMean at position 1: 1
Mean at position 2: 1.5
Mean at position 3: 2
Mean at position 4: 2.5
Mean at position 5: 3
In this method, we are using the map function wot compute the mean at each potion in the input array by updating the cumulative sum and storing the means in the means array.
Example: In this example, we will find the mean at every point in JavaScript using the Array Map Method
JavaScript
const arr = [5,4,3,2,1];
let s = 0;
const means = arr.map((value, index) => {
s += value;
const res = s / (index + 1);
console.log(`Mean at position ${index + 1}: ${res}`);
return res;
});
OutputMean at position 1: 5
Mean at position 2: 4.5
Mean at position 3: 4
Mean at position 4: 3.5
Mean at position 5: 3
In this method, we are using the reduce function to compute the mean at each potion in the array by updating the cumulative sum and storing the mean in the means array.
Example: In this example, we will find the mean at every point in JavaScript using the Array Reduce Method
JavaScript
const arr = [1, 2, 3, 4, 5];
const means = arr.reduce((acc, v, idx) => {
const s = acc.sum + v;
const res = s / (idx + 1);
acc.means.push(res);
console.log(`Mean at position ${idx + 1}: ${res}`);
return { sum: s, means: acc.means };
}, { sum: 0, means: [] });
OutputMean at position 1: 1
Mean at position 2: 1.5
Mean at position 3: 2
Mean at position 4: 2.5
Mean at position 5: 3
Using a Generator Function
In this approach, we use a generator function to yield the mean at each position in the array. Generators are a special type of function that can be paused and resumed, making them suitable for iterating over sequences of values. This method allows for a clean and efficient way to compute the means without the need for additional storage.
Example:
JavaScript
function* calculateMean(arr) {
let cumulativeSum = 0;
for (let i = 0; i < arr.length; i++) {
cumulativeSum += arr[i];
yield cumulativeSum / (i + 1);
}
}
const arr = [1, 2, 3, 4, 5];
const meanGenerator = calculateMean(arr);
for (let mean of meanGenerator) {
console.log(`Mean at position ${arr.indexOf(mean) + 1}: ${mean}`);
}
OutputMean at position 1: 1
Mean at position 0: 1.5
Mean at position 2: 2
Mean at position 0: 2.5
Mean at position 3: 3
Method 4: Using a Functional Approach with Array.map() and Array.slice()
In this approach, we use the Array.map() method along with Array.slice() to create a new array containing the means at each position. We iteratively calculate the mean for each position by slicing the array from index 0 to the current position and then computing the sum and mean.
Example:
JavaScript
function calculateMeanUsingMap(arr) {
return arr.map((_, index) => {
const currentSlice = arr.slice(0, index + 1);
const sum = currentSlice.reduce((acc, num) => acc + num, 0);
return sum / currentSlice.length;
});
}
const arr = [1, 2, 3, 4, 5];
const means = calculateMeanUsingMap(arr);
means.forEach((mean, index) => {
console.log(`Mean at position ${index + 1}: ${mean}`);
});
OutputMean at position 1: 1
Mean at position 2: 1.5
Mean at position 3: 2
Mean at position 4: 2.5
Mean at position 5: 3
Similar Reads
JavaScript Array findIndex() Method
The findIndex() method in JavaScript is a powerful tool for locating the first element in an array that satisfies a provided testing function. This guide provides a comprehensive overview of how to use findIndex() effectively, enhancing your ability to manipulate arrays. Syntax array.findIndex(funct
5 min read
JavaScript Array every() Method
The every() method iterates over each array element, returning true if the provided function returns true for all elements. It returns false if the function returns false for any element. This method does not operate on empty elements and leaves the original array unchanged.Syntaxarray.every(callbac
3 min read
Print all Even Numbers in a Range in JavaScript Array
We have to find all even numbers within a given range. To solve this question we are given the range(start, end) in which we have to find the answer. There are several ways to print all the even numbers in a range in an array using JavaScript which are as follows: Table of Content Using for Loop in
3 min read
Javascript Program to Find closest number in array
Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples: Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input :arr[] = {2, 5, 6, 7, 8, 8, 9};
4 min read
JavaScript Array find() Method
The find() method in JavaScript looks through an array and returns the first item that meets a specific condition you provide. If no item matches, it returns undefined. It skips any empty space in the array and doesnât alter the original array.Syntax:array.find(function(currentValue, index, arr), th
3 min read
JavaScript â Min Element in an Array
These are the following ways to find the minimum element in JS array:Note: You must add a conditional check for checking whether the given array is empty or not, if the array is not empty then you can use the given below approaches to find out the minimum element among them.1. Using Math.min() Metho
3 min read
Find Second Smallest Element in an Array in JavaScript
JavaScript allows us to compute the Second Smallest Element within a given array. The task involves iterating through the array, identifying the smallest and second smallest element in the array. There are several approaches to finding the second smallest element in an array using Javascript which a
2 min read
JavaScript - Insert Elements at a Given Position in an JS Array
To insert an element at a specific position in a JavaScript array, the JS splice() method is used. JavaScriptlet a = [10, 20, 30, 40]; let e = 50; let i = 2; a.splice(i - 1, 0, e); console.log(a);Output[ 10, 50, 20, 30, 40 ] Table of ContentUsing built-in MethodWriting Your Own MethodUsing built-in
1 min read
Find Mode of an Array using JavaScript
To find the mode in an array with JavaScript, where the mode is the number occurring most frequently. Various approaches can be employed to find the mode, and an array may have multiple modes if multiple numbers occur with the same highest frequency. Example:Input:3, 6, 4, 6, 3, 6, 6, 7 , 6, 3 , 3Ou
4 min read
How to define custom Array methods in JavaScript?
JavaScript arrays are versatile data structures used to store collections of items. When you want to iterate through the elements of an array, it's common to use loops like for, for...of, or forEach. However, there's a nuance when it comes to iterating through arrays that have additional properties
2 min read