find the median of a list of numbers in javascript

To find the median of a list of numbers in JavaScript, we can follow these steps:

  1. Sort the list of numbers in ascending order.
  2. Check if the length of the list of numbers is odd or even.
  3. If the length of the list is odd, return the number in the middle of the list.
  4. If the length of the list is even, return the average of the two numbers in the middle of the list.

Here's the JavaScript code to implement this algorithm:

index.tsx
function median(numbers) {
  // sort the numbers in ascending order
  numbers.sort(function(a, b) {
    return a - b;
  });

  // get the middle index
  var middle = Math.floor(numbers.length / 2);

  // check if the length of the list is odd or even
  if (numbers.length % 2 == 0) {
    // return the average of the two numbers in the middle of the list
    return (numbers[middle - 1] + numbers[middle]) / 2;
  } else {
    // return the number in the middle of the list
    return numbers[middle];
  }
}

// example usage
var list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
var result = median(list);
console.log(result); // output: 4
632 chars
24 lines

gistlibby LogSnag