Codewars median
codewars 6kyu (7kyu
by trentHarlem
JavaScript
function median(array) {
const sorted = array.slice().sort((a, b) => a - b);
return (array.length % 2 === 0) ?
(sorted[array.length / 2] + sorted[array.length / 2 - 1]) / 2 :
sorted[Math.ceil(array.length / 2)]
}
//console.log(Math.ceil(5 / 2))
//console.log(1 % 2)
//const test = [33, 99, 100, 30, 29, 50].sort((a, b) => a - b)
//const test2 = [3, 2, 1].slice().sort((a, b) => a - b)
//console.log(test2[Math.ceil(test2.length / 2)])
console.log(median([33, 99, 100, 30, 29, 50]), 41.5)
console.log((median([3, 2, 1]), 2))
//console.log('test', [33, 99, 100, 30, 29, 50].sort((a, b) => a - b).reduce((a, c) => a + c) / 6)