Get average value of items in a javascript array


Sun Jan 05 2020 19:39:47 GMT+0000 (UTC)

Saved by @bezequi #javascript #webdev #arrays #math

const arrAvg = arr => arr.reduce((a,b) => a + b, 0) / arr.length
// arrAvg([20, 10, 5, 10]) -> 11.25

In this function, we first use reduce() to reduce all values in our array to a single sum. Once we have the sum we simply divide this value by the length of the array. The result is the average value which then gets returned.