To find the median of an array in JavaScript, we can follow these steps:
Here's the code:
index.tsx170 chars6 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.tsx122 chars6 lines
gistlibby LogSnag