Created
March 16, 2022 00:01
-
-
Save kevinmmartins/38d0d710a8fab39f1cd4f7cc310ccd77 to your computer and use it in GitHub Desktop.
Get the average number from the middle of the list if the list is even or the middle number when the list is odd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const isEven = (num) => (num % 2 === 0) | |
const getNumber = (array = []) => { | |
const size = array.length | |
if(isEven(size)){ | |
const index = size/2 | |
return (array[index]+array[index-1])/2 | |
} | |
const index = (size-1)/2 | |
return array[index] | |
} | |
console.log(getNumber([1,4,5])); // 4 | |
console.log(getNumber([1,4,5,6])); // 4.5 | |
console.log(getNumber([1,4,5,6])); // 4.5 | |
console.log(getNumber([1,4,5,6,8])); // 5 | |
console.log(getNumber([1,4,5,5,8,3])); // 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment