The RMS (Root Mean Square) value of an array is the square root of the mean of the squares of its elements.
To calculate the RMS value:
- Square each element of the array.
- Calculate the sum of the squared values.
- Divide the sum by the number of elements to get the mean.
- Calculate the square root of the mean.
Formula:
RMS = √((a₁² + a₂² + a₃² + ... + aₙ²) / n)Approach 1: Using map(), reduce() and Math.sqrt()
In this approach, the map() method is used to calculate the square of each element. The reduce() method then calculates their sum, and Math.sqrt() calculates the square root of the mean.
Example: Calculates the RMS value of the elements in an array.
function calculateRMS(arr) {
// Calculate the square of each element
let squares = arr.map(val => val * val);
// Calculate the sum of squared values
let sum = squares.reduce((acc, val) => acc + val, 0);
// Calculate and return RMS
let mean = sum / arr.length;
return Math.sqrt(mean);
}
let arr = [5, 9, 3, -7, -4];
let rms = calculateRMS(arr);
console.log(rms);
Output
6
Approach 2: Using a Single-Line Function
The same calculation can be performed using a concise arrow function. The map() and reduce() methods are chained together to calculate the sum of squares, which is then divided by the array length and passed to Math.sqrt().
Example: Calculates the RMS value using a single-line arrow function.
const calculateRMS = arr =>
Math.sqrt(
arr
.map(val => val * val)
.reduce((acc, val) => acc + val, 0) / arr.length
);
let arr = [5, 9, 3, -7, -4];
let rms = calculateRMS(arr);
console.log(rms);
Output
6
Note: Using a one-line function does not necessarily make the code faster or use less memory. The main advantage is that it provides a more concise way to express the same calculation.