Created
October 11, 2019 20:21
-
-
Save nachodd/d2d5293ed3ac5997c30a40aeff54b58c to your computer and use it in GitHub Desktop.
Average Multidimensional Array Javascript (recursive)
This file contains hidden or 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 averange = (input) => { | |
const {sum, count} = sumAndCount(input) | |
return sum/count | |
} | |
const sumAndCount = (arr) => { | |
let count = 0 | |
const sum = arr.reduce((acc, element) => { | |
if(Array.isArray(element)) { | |
const res = sumAndCount(element) | |
count += res.count | |
acc += res.sum | |
} else { | |
count += 1 | |
acc += element | |
} | |
return acc | |
}, 0) | |
return {count, sum} | |
} | |
// Given: | |
const data = [[1,2,3], [4,5,6], 7] | |
// Use: | |
averange(data) | |
// Outputs: 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment