File tree Expand file tree Collapse file tree 1 file changed +23
-3
lines changed
Expand file tree Collapse file tree 1 file changed +23
-3
lines changed Original file line number Diff line number Diff line change 66// or 'list' has mixed values (the function is expected to sort only numbers).
77
88function calculateMedian ( list ) {
9- const middleIndex = Math . floor ( list . length / 2 ) ;
10- const median = list . splice ( middleIndex , 1 ) [ 0 ] ;
11- return median ;
9+ // Check if input is an array
10+ if ( ! Array . isArray ( list ) ) {
11+ return null ;
12+ } else {
13+ // Get only numeric values
14+ const numericList = list . filter ( ( item ) => typeof item === "number" ) ;
15+ // Check if its empty after filtering
16+ if ( numericList . length === 0 ) {
17+ return null ;
18+ }
19+ // Sort the list by numeric value
20+ numericList . sort ( ( a , b ) => a - b ) ;
21+ // Get middle index
22+ const middleIndex = Math . floor ( numericList . length / 2 ) ;
23+ // Check if length is even or odd
24+ if ( numericList . length % 2 === 0 ) {
25+ // Return average of two middle numbers
26+ return ( numericList [ middleIndex - 1 ] + numericList [ middleIndex ] ) / 2 ;
27+ } else {
28+ // Return middle number by index
29+ return numericList [ middleIndex ] ;
30+ }
31+ }
1232}
1333
1434module . exports = calculateMedian ;
You can’t perform that action at this time.
0 commit comments