find the median of all elements in an array in typescript

To find the median of all elements in an array in TypeScript, you can follow these steps:

  1. Sort the array in ascending order using the Array.sort() method.
  2. Check if the length of the array is odd or even.
  3. If it is odd, return the middle element; if it is even, return the average of the middle two elements.

Here's the TypeScript code to accomplish this:

index.ts
function median(arr: number[]): number {
  arr.sort((a, b) => a - b) // sort in ascending order

  const mid = Math.floor(arr.length / 2)

  if (arr.length % 2 === 0) {
    return (arr[mid - 1] + arr[mid]) / 2 // average of middle two elements
  } else {
    return arr[mid] // middle element
  }
}
299 chars
12 lines

This function takes an array of numbers as input and returns the median value. You can test it with the following code:

index.ts
const arr = [1, 3, 2, 4, 5]
console.log(median(arr)) // expected output: 3
75 chars
3 lines

Note that the arr.sort() method modifies the original array, so if you don't want to change the order of the elements, you should make a copy of the array before sorting.

gistlibby LogSnag