Find the average for an array of numbers in JavaScript?

Answered
itsbambi asked this question 21 days ago
itsbambi 21 days ago

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 11 days ago

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 11 days ago
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 11 days ago

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