JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

How to Calculate Averages and Medians of Arrays

September 6, 2016 by Krishna Srinivasan Leave a Comment

Finding the average and the median of an array using JavaScript can be a fairly painless process. If you do it right, it should only take a few lines of code to calculate the correct averages and medians for any given array.

The average, which is the sum of all the values divided by the number of values, you’ll need to find the length of the array, sum up all of the values using the .reduce() method (the .reduce() method will reduce the values of an array to a single value by adding them all together), and divide the sum by the array’s length.

var values = [4, 9, 3, 17, 12] 
var sum = values.reduce((previous, current) => current += previous);
var avg = sum / values.length;
// avg = 9

To find the median or the value or values that lie in the middle of an array when the array is in numerical order, you need to .sort() the array to make sure that the values are properly arranged, then get the mean of the middle values, like this:

var values = [7, 6, 29, 3, 88, 11];
values.sort((a, b) => a - b);
var lowMiddle = Math.floor((values.length - 1) / 2);
var highMiddle = Math.ceil((values.length - 1) / 2);
var median = (values[lowMiddle] + values[highMiddle]) / 2;
// median = 20

Filed Under: JavaScript Tagged With: Arrays, Average, Medians

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved