Member-only story

JavaScript Interview Prep: How to find the median in the array

Marika Lam
Jun 30, 2024

--

Prompt

Solution

The sort() method of Array instances sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. To sort elements without mutating the orignal array, use toSorted().

Math.floor static method always rounds down and returns the largest integer less than or equal to a given number. It is opposite of Math.ceil.

function findMedian(arr) {

const sort = arr.sort((a,b)=>{
return a-b
});

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

return sort[middleIndex];

}

--

--

No responses yet