OneCompiler

[JavaScript] How to compute average of all elements from an array?

I want to find average of all elements from an array, how can I do that in Javascript?

1 Answer

4 years ago by

Below is the simplest and efficient way to calculate the average of all the elements present in an array:

let numbers = [ 1, 2, 3, 4, 5 ];
let sum = numbers.reduce((a, b) => a + b);
console.log("Average: ", sum/numbers.length);

Try running the above code online here: https://onecompiler.com/javascript/3xnkf6s72

4 years ago by Meera