Skip to content

Instantly share code, notes, and snippets.

@kevinmmartins
Created March 16, 2022 00:01
Show Gist options
  • Save kevinmmartins/38d0d710a8fab39f1cd4f7cc310ccd77 to your computer and use it in GitHub Desktop.
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
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