xxxxxxxxxx
//given odd number of elements
let arr = [9,4,6,3,8]
//sort the array
arr.sort((a, b) => a - b)
//declare median variable
let median;
//if else block to check for even or odd
if(arr.length%2 != 0){
//odd case
//find middle index
let middleIndex = Math.floor(arr.length/2)
//find median
median = arr[middleIndex]
}else{
//even case
//find middle index
let middleIndex = Math.floor(arr.length/2)
//find median
median = arr[middleIndex] + arr[middleIndex + 1]
}
//print median
console.log(median)
xxxxxxxxxx
//#Source https://bit.ly/2neWfJ2
const median = arr => {
const mid = Math.floor(arr.length / 2),
nums = [arr].sort((a, b) => a - b);
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
};
console.log(median([5, 6, 50, 1, -5]));
console.log(median([1, 2, 3, 4, 5]));