Find the average for an array of numbers in JavaScript?

Answered
itsbambi asked this question 7 months ago
itsbambi on Jan 4

I have an array of numbers that looks similar to this:

[21, 931, 354, 12, 1254, 432, 234, 654, 51, 90, 43]

How can I get the average of all these numbers?

This is all in JavaScrpt, btw.

3 suggested answers
looper003 on Jan 14

A function you can use:

function getAverage(array) {
  let total = 0

  for (var i=0; i < array.length; i++) {
    total += array[i]
  }

  return Math.round(total / array.length)
}

For your example, it would return:

getAverage([21, 931, 354, 12, 1254, 432, 234, 654, 51, 90, 43])

// 371
0 replies
coderguy on Jan 14
array.reduce((a, b) => a + b) / array.length

Code breakdown:

  1. Sum the total of each item in the array using the reduce() method.
  2. Divide the total sum by the number of items in the array (array.length).

If you want to round the result to the nearest whole number, update your code to this:

Math.round(array.reduce((a, b) => a + b) / array.length)
0 replies
yaboy01 on Jan 14

A method that uses lodash:

const _ = require("lodash")

const getAverage = (array) => _.chain(array)
 .sum()
 .divide(array.length)
 .round(1)
 .value()

// usage
getAverage(myArray)
0 replies
Answered