Skip to content

Instantly share code, notes, and snippets.

@vunderkind
Created February 10, 2022 22:18
Show Gist options
  • Save vunderkind/51682789bf912a7a7468a7d565e8e29b to your computer and use it in GitHub Desktop.
Save vunderkind/51682789bf912a7a7468a7d565e8e29b to your computer and use it in GitHub Desktop.
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