Javascript – Get average value of a numeric array using Underscore

Underscore provides a lot of useful helper functions in Javascript programming. Here is an example of getting an average value of a numeric array.

<!DOCTYPE html>
<html>
<head>
  <title>Get average value of an array using underscore</title>
  <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
</head>
<body>
  <div id="average"></div>
  <script type="text/javascript">
    var values = [13, 17, 11, 24, 56, 31, 27, 19];
    document.getElementById("average").innerHTML = arrayAverage(values);

    function arrayAverage(arr) {
      return _.reduce(arr, function(memo, num) {
        return memo + num;
      }, 0) / (arr.length === 0 ? 1 : arr.length);
    }
  </script>
</body>
</html>

 

Done =)

Reference:

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.