We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent f9f7dc0 commit 31bcc22Copy full SHA for 31bcc22
1 file changed
Sprint-1/fix/median.js
@@ -12,10 +12,13 @@ function calculateMedian(list) {
12
const nums = list.filter((x) => typeof x === "number" && isFinite(x));
13
// Return null if no valid numbers remain
14
if (nums.length === 0) return null;
15
-
16
- const sorted = [...nums].sort((a, b) => a - b);
+ // Sort the numbers in ascending order
+ // filter already returns a new array so need to spread before spreading
17
+ const sorted = nums.sort((a, b) => a - b);
18
+ // Find the middle index of the sorted array
19
const middleIndex = Math.floor(sorted.length / 2);
20
+ // If odd length, return the middle index
21
+ // If even length, return the average of the two middle elements
22
return sorted.length % 2 !== 0
23
? sorted[middleIndex]
24
: (sorted[middleIndex - 1] + sorted[middleIndex]) / 2;
0 commit comments