Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript program for Mean of range in an array
Given an array of numbers and a range, the goal is to calculate the mean of all the numbers within that range. This problem can be approached in various ways, but in this tutorial, we will explore a simple and efficient solution using JavaScript.
Before we begin, let's define what we mean by "mean". In mathematics, the mean (also known as the average) is calculated by adding up all the values in a set of numbers and then dividing the sum by the number of values. In the context of an array, the mean of a range of values is the average of all the values in that range.
Problem Statement
Given an array of numbers and a range consisting of two numbers, the goal is to calculate the mean of all the numbers within that range. The range is inclusive, meaning it should include both the first and last numbers in the range. The function should take in the array and range as input and output the mean of the numbers within the range. If the input array is empty, the function should return null. If the range is invalid (i.e., the first number is greater than the second number), the function should return null as well.
Let's understand this with some examples:
Example 1
Input: Array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Range: [3, 7]
Output: Mean of range [3, 4, 5, 6, 7] is 5.00
In Example 1, we have an array of numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and the range [3, 7]. The mean of the range [3, 4, 5, 6, 7] is 5.00.
Example 2
Input: Array: [2, 4, 6, 8, 10, 12]
Range: [1, 5]
Output: Mean of range [2, 4, 6, 8, 10] is 6.00
In Example 2, we have an array of numbers [2, 4, 6, 8, 10, 12] and the range [1, 5]. The mean of the range [2, 4, 6, 8, 10] is 6.00.
Example 3
Input: Array: [3, 5, 7, 9, 11, 13]
Range: [7, 3]
Output: null
In Example 3, the range [7, 3] is invalid because the first number is greater than the second number, so the output should be null.
Example 4
Input: Array: []
Range: [1, 5]
Output: null
In Example 4, the input array is empty, so the output should also be null.
Algorithm
STEP 1 ? Define the function 'meanInRange' that takes two parameters, an array 'arr' and a range 'range'.
STEP 2 ? Check if the length of the input array 'arr' is zero. If it is, return null.
STEP 3 ? Destructure the 'range' array into two variables 'start' and 'end'.
STEP 4 ? Check if the value of 'start' is greater than 'end'. If it is, return null.
STEP 5 ? Use the 'slice' method to extract a subarray from the input array 'arr' that includes only the elements between the start and end indices of the given range.
STEP 6 ? Use the 'reduce' method to calculate the sum of all the elements in the subarray.
STEP 7 ? Divide the sum by the length of the subarray to obtain the mean.
STEP 8 ? Return the mean as a string formatted to two decimal places, along with a message that indicates the range of the values used to compute the mean.
Implementation
In this implementation, we define a function 'meanInRange' that takes in an array 'arr' and a range 'range' as input. The function first checks if the input array is empty or if the range is invalid and returns null if either condition is true. Otherwise, it slices the input array to get the range, calculates the sum of the numbers in the range using 'reduce', and calculates the mean.
function meanInRange(arr, range) {
if (arr.length === 0) {
return null; // return null if the input array is empty
}
const [start, end] = range;
if (start > end) {
return null; // return null if the range is invalid
}
const rangeArr = arr.slice(start - 1, end); // slice the array to get the range
const sum = rangeArr.reduce((acc, num) => acc + num, 0); // calculate the sum
const mean = sum / rangeArr.length; // calculate the mean
// return the mean rounded to two decimal places
return `Mean of range [${rangeArr}] is ${mean.toFixed(2)}`;
}
// Example usage:
console.log(meanInRange([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [3, 7]));
console.log(meanInRange([2, 4, 6, 8, 10, 12], [1, 5]));
console.log(meanInRange([3, 5, 7, 9, 11, 13], [7, 3]));
console.log(meanInRange([], [1, 5]));
Mean of range [3,4,5,6,7] is 5.00 Mean of range [2,4,6,8,10] is 6.00 null null
Alternative Approach
Here's a more flexible version that returns only the numeric value instead of a formatted string:
function calculateMean(arr, range) {
if (arr.length === 0) {
return null;
}
const [start, end] = range;
if (start > end) {
return null;
}
const rangeArr = arr.slice(start - 1, end);
const sum = rangeArr.reduce((acc, num) => acc + num, 0);
return parseFloat((sum / rangeArr.length).toFixed(2));
}
// Example usage:
console.log(calculateMean([1, 2, 3, 4, 5], [2, 4])); // 3.00
console.log(calculateMean([10, 20, 30, 40], [1, 3])); // 20.00
console.log(calculateMean([], [1, 3])); // null
3 20 null
Key Points
- The range is 1-indexed (first element is at position 1, not 0)
- The range is inclusive of both start and end positions
- Edge cases (empty array, invalid range) return null
- The slice method extracts elements from start-1 to end (exclusive)
- The reduce method efficiently sums all elements in the range
Conclusion
In this tutorial, we explored how to calculate the mean of a range of values within an array using JavaScript. We covered the problem statement, provided a step-by-step algorithm, and implemented a complete solution with proper error handling for edge cases like empty arrays and invalid ranges.
