average in array

There are many places where the average number is used in the business. To obtain the average value in the array, we need to sum the numbers and then divide by  values the length. The steps are as follows:

    Get the length of the array (length)

    Sum (sum)

    Get average (sum/length)

let values = [44, 56, 3, 66, 10, 4, 100, 23]

const avg = arr => {
  let len = arr.length
  let total = arr.reduce((prev, cur) => cur += prev)
  return total /= len
}

console.log(avg(values)) // 38.25

Isn’t it very simple, save it, it’s very convenient when you use it~

 

Supongo que te gusta

Origin blog.csdn.net/zhangxueyou2223/article/details/128816616
Recomendado
Clasificación