Q:

Write a JavaScript program to get the median of an array of numbers

0

 Write a JavaScript program to get the median of an array of numbers.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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]));

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now