Find average and median of a given array in Javascript.
Problem
We are given an array that is hopefully comprised of numbers. Find average and median.
Get average
Calculate sum, length and use them to get the average.
1
2
3
4
5
6
|
const arr = [3, 7, 2, 6, 5, 4, 9];
const sum = arr.reduce((sum, val) => (sum += val));
const len = arr.length;
console.log("average: ", sum / len);
// 5.142857142857143
|
Sort array. Median formula is different depending on whether length of array is odd or even.
- Array length = odd => median is the average of the two middle numbers
- Array length = odd => pick the middle number as median
1
2
3
4
5
6
7
8
|
const arrSort = arr.sort();
const mid = Math.ceil(len / 2);
const median =
len % 2 == 0 ? (arrSort[mid] + arrSort[mid - 1]) / 2 : arrSort[mid - 1];
console.log("median: ", median);
// 5
|
One important pre-requisite
Although the above arrangement works, it is always a good idea to filter out our arrays for undesired elements!
So, putting everything together.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
const arrOrig = [3, 7, 2, 6, 5, 4, 9, undefined];
const arr = arrOrig.filter(val => !!val);
const sum = arr.reduce((sum, val) => (sum += val));
const len = arr.length;
console.log("average: ", sum / len);
const arrSort = arr.sort();
const mid = Math.ceil(len / 2);
const median =
len % 2 == 0 ? (arrSort[mid] + arrSort[mid - 1]) / 2 : arrSort[mid - 1];
console.log("median: ", median);
// 5
|
Update 24-Mar-20: Correction to median calculation (thanks to Deam Chirstopher’s comment below).