find the median of a list of numbers in typescript

To find the median of a list of numbers in TypeScript, we can use the following steps:

  1. Sort the array of numbers in ascending order
  2. If the array length is odd, return the middle value
  3. If the array length is even, return the average of the two middle values.

Here's the code implementation:

index.ts
function findMedian(numbers: number[]): number {
  numbers.sort((a, b) => a - b); // sort array in ascending order

  const middleIndex = Math.floor(numbers.length / 2);

  if (numbers.length % 2 === 0) {
    // array length is even
    return (numbers[middleIndex - 1] + numbers[middleIndex]) / 2;
  } else {
    // array length is odd
    return numbers[middleIndex];
  }
}

const numbers = [10, 5, 7, 3, 2, 6, 4, 8, 9, 1];
const median = findMedian(numbers); // 5.5
469 chars
17 lines

In this code, we define a function findMedian that takes an array of numbers as its argument. We then sort the array in ascending order using the sort method with a compare function. We find the middle index of the array by dividing the length of the array by 2, using the Math.floor function to return an integer. If the length of the array is odd, we return the value at the middle index using the bracket notation. If the length of the array is even, we take the average of the two middle values using the bracket notation and the addition and division operators. Finally, we call the findMedian function on an example numbers array to find the median, which is 5.5 for this example.

gistlibby LogSnag