How to find mean value from an array in Javascript
Hey guys, welcome back to the DevMaesters website. In this article I am going to be showing you how you can get the mean value from an array in Javascript.
Lets say you have the following statistics values [2,4,5,2,9,5] and you want to find its mean all you need to do is add all the elements in the array together and divide by the numbers of elements in the array as show below
function getMean(data) {
//sum all the elements in the array
let sum = data.reduce((a, b) => a + b)
// divide the sum of the elements by the number of elements in the array
let val = sum / data.length
// return the value
return val
}
let value = [2, 4, 5, 2, 9, 5]
//call getMean function
let result = getMean(value)
console.log("mean", result)
Calling the function in the code above ouputs the mean value in the console.
Conclusion
That's it! Now you know how to calculate the mean value of an array in JavaScript. If you have any questions, please feel free to leave a comment below.
Happy coding!