Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

RMS Value Of Array in JavaScript

  • Last Updated : 14 Feb, 2019

The RMS (Root mean square) value of a distribution is the square root of the mean of the squares of the elements. The formula to find RMS value are given below:

 RMS = \sqrt{\frac{{a_{1}}^{2} + {a_{2}}^{2} + {a_{3}}^{2} + {a_{4}}^{2} + ... + {a_{N}}^{2}}{N}}

To calculate RMS value of an array, first need to square all the elements in the array. Then, take the mean of those squared value by summing it and dividing it by the number of the elements and finally take the square root of that number.


let CalculateRMS = function (arr) {
    // Map will return another array with each 
    // element corresponding to the elements of
    // the original array mapped according to
    // some relation
    let Squares = => (val*val));
    // Function reduce the array to a value
    // Here, all the elements gets added to the first
    // element which acted as the accumulator initially.
    let Sum = Squares.reduce((acum, val) => (acum + val));
    Mean = Sum/arr.length;
    return Math.sqrt(Mean);
let arr = [5, 9, 3, -7, -4];
let Rms = CalculateRMS(arr);



Now the above script converted into single line script. To write the above script into single line, first convert the arr to another array of squares using Map function which returns an array. Now apply reduce on that array directly which will return a single value (sum of all the squares). Sum of square of number divided by number of elements and get the square root. It will produce RMS value.


let CalculateRMS = (arr) => Math.sqrt(
                .map( val => (val * val))
                .reduce((acum, val) => acum + val)
// The above can be written without any 
// line breaks in between as a single-line.
// For the sake of easy 
// understanding it is written like that.
let arr = [5, 9, 3, -7, -4];
let RMS = CalculateRMS(arr);



Benefits Of Writing An One-line Functions
The less code will require less memory, so it will take less time for any Web Browser to load the script with less memory. Further, the browser renders the WebPage by executing the code line-by-line, so any operation on website involving One-line functions will respond much quickly as compared to the normal functions.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!