[JavaScript] Median Calculation Sample Code and Math.js Usage Examples

Tadashi Shigeoka ·  Thu, October 17, 2019

I’ll introduce sample code for calculating median in JavaScript (ES5/ES6) and usage examples of the Math.js numerical computation library.

JavaScript

Background: Want to Calculate Median in JavaScript

  • Want to calculate median in JavaScript
  • Don't want to reinvent the wheel, so basically plan to use math.median from Math.js
  • Also created a custom median function for when libraries can't be used

Calculate Median with Math.js

Install Math.js

npm install mathjs

Install math.js

math.median Usage Examples

math.median(5, 2, 7)        // returns 5

math.median([3, -1, 5, 7])  // returns 4

JavaScript Sample Code for Calculating Median

median for ES5

var median = function (array) {
  if (array.length === 0) {
    return 0;
  }

  array.sort(function(a, b){
    return a - b;
  });

  var half = Math.floor(array.length / 2);

  if (array.length % 2) {
    return array[half];
  } else {
    return (array[half - 1] + array[half]) / 2;
  }
};

median for ES6 (ES2015)

const median = (array) => {
  if (array.length === 0) {
    return 0;
  }

  array.sort((a, b) => {
    return a - b;
  });

  const half = Math.floor(array.length / 2);

  if (array.length % 2) {
    return array[half];
  } else {
    return (array[half - 1] + array[half]) / 2;
  }
};

That’s all from the Gemba.

Reference Information