find the median of all elements in an array in javascript

To find the median of an array in JavaScript, we can follow these steps:

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

Here's the code:

index.tsx
function median(arr) {
  arr.sort((a, b) => a - b);
  const mid = Math.floor(arr.length / 2);
  return arr.length % 2 !== 0 ? arr[mid] : (arr[mid - 1] + arr[mid]) / 2;
}
170 chars
6 lines

We first sort the array using the sort() method and a custom compare function that sorts the elements in ascending order. Then, we calculate the middle index of the array using Math.floor(arr.length / 2).

If the length of the array is odd, we simply return the middle element using arr[mid].

If the length of the array is even, we take the average of the two middle elements using (arr[mid - 1] + arr[mid]) / 2.

Here's an example usage of the function:

index.tsx
const arr = [1, 2, 3, 4, 5];
console.log(median(arr)); // 3

const arr2 = [1, 2, 3, 4];
console.log(median(arr2)); // 2.5
122 chars
6 lines

gistlibby LogSnag