Created
February 10, 2022 22:18
-
-
Save vunderkind/51682789bf912a7a7468a7d565e8e29b to your computer and use it in GitHub Desktop.
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
let company = { // the same object, compressed for brevity | |
sales: [{name: 'John', salary: 1000}, {name: 'Alice', salary: 1600 }], | |
development: { | |
sites: [{name: 'Peter', salary: 2000}, {name: 'Alex', salary: 1800 }], | |
internals: [{name: 'Jack', salary: 1300}] | |
} | |
}; | |
// The function to do the job | |
function sumSalaries(department) { | |
if (Array.isArray(department)) { // case (1) | |
return department.reduce((prev, current) => prev + current.salary, 0); // sum the array | |
} else { // case (2) | |
let sum = 0; | |
for (let subdep of Object.values(department)) { | |
sum += sumSalaries(subdep); // recursively call for subdepartments, sum the results | |
} | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment