As I was exploring how to calculate the median value of an array, my initial step was determining whether the array had an odd or even number of elements.
- If the number of elements is odd, then the middle element will be logged in the console.
- If there's an even number of elements, I intended for the console to log 'Not an odd number of numbers'.
While I am aware that there might be simpler methods to find the median of an array, I prefer to try and solve it on my own. Currently, I'm stuck on why the number 1
is being logged in the second test case, despite the array having an even number of elements? It seems to work correctly in the first and third tests but not the second one...what could be going wrong?
function median (arr) {
let sorted = arr.sort((a, b) => a-b)
let midIndex = sorted.splice(0, sorted.length / 2)
if (arr.length %2 != 0) {
return midIndex[midIndex.length-1]
} else {
return "Not an odd number of numbers"
}
}
try {
let result = median([4, 8, 2, 4, 5])
console.log(result) // -> 4
result = median([-5, 1, 5, 2, 4, 1]) // -> 1
console.log(result)
result = median([5, 1, 1, 1, 3, -2, 2, 5, 7, 4, 5, 6]) // -> Not an odd number of numbers
console.log(result)
} catch (e) {
console.error(e.message)
}