RMS Value Of Array in JavaScript
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 is given below:
To calculate the RMS value of an array, first need to square all the elements in the array. Then, take the mean of those squared values by summing it and dividing it by the number of the elements and finally take the square root of that number.
Example: In this example, we will find out the root mean square value of the elements of an array.
javascript
<script>
let CalculateRMS = function (arr) {
let Squares = arr.map((val) => (val*val));
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);
console.log(Rms);
</script>
|
Output:
6
Now the above script is converted into a single-line script. To write the above script into a single line, first, convert the arr to another array of squares using the Map function which returns an array. Now apply to reduce on that array directly which will return a single value (sum of all the squares). Sum of the square of the number divided by the number of elements and get the square root. It will produce RMS value.
Example 2: In this example, we will write a single-line function for RMS.
javascript
<script>
let CalculateRMS = (arr) => Math.sqrt(
arr
.map( val => (val * val))
.reduce((acum, val) => acum + val)
/arr.length
);
let arr = [5, 9, 3, -7, -4];
let RMS = CalculateRMS(arr);
console.log(RMS);
</script>
|
Output:
6
Benefits Of Writing 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 the website involving One-line functions will respond much more quickly as compared to the normal functions.
Last Updated :
03 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...