Reputation: 557
I have a function called nestedEvenSum
that takes an object
as a parameter and loops through the object
trying to find values that are even numbers. When it finds an even number, it adds that to the variable sum
. Here is my code:
function nestedEvenSum (obj) {
let sum = 0;
function inner(obj) {
for (let i in obj) {
if (typeof obj[i] === "number" && obj[i] % 2 === 0) sum += obj[i];
if (typeof obj[i] === 'object') return inner(obj[i]);
}
}
inner(obj);
return sum;
}
I give my function the following object:
var obj2 = {
a: 2,
b: {b: 2, bb: {b: 3, bb: {b: 2}}},
c: {c: {c: 2}, cc: 'ball', ccc: 5},
d: 1,
e: {e: {e: 2}, ee: 'car'}
};
and my loop keeps returning 6
instead of 10
. For some reason, the for loop is exiting after the recursive inner()
calls unwind for the second key (b). I'm not sure why the for loop isn't continuing on with the three remaining keys. If someone could point me in the right direction, I'd appreciate it. Thanks!
Upvotes: 0
Views: 225
Reputation: 386550
Beside the false return statement for objects, you could take a single function and add the returned result of the function for nested objects.
function nestedEvenSum(obj) {
let sum = 0;
for (let i in obj) {
if (typeof obj[i] === "number" && obj[i] % 2 === 0) sum += obj[i];
if (obj[i] && typeof obj[i] === 'object') sum += nestedEvenSum(obj[i]);
}
return sum;
}
var obj2 = { a: 2, b: { b: 2, bb: { b: 3, bb: { b: 2 } } }, c: { c: { c: 2 }, cc: 'ball', ccc: 5 }, d: 1, e: { e: { e: 2 }, ee: 'car' } };
console.log(nestedEvenSum(obj2));
Upvotes: 1
Reputation: 3408
Don't return inside of your loop. That is going to exit your recursion. Instead you need to CALL the function again which is not the same as returning it.
function nestedEvenSum (obj) {
let sum = 0;
function inner(obj) {
for (let i in obj) {
if (typeof obj[i] === "number" && obj[i] % 2 === 0) sum += obj[i];
if (typeof obj[i] === 'object') inner(obj[i]);
}
}
inner(obj);
return sum;
}
var obj2 = {
a: 2,
b: {b: 2, bb: {b: 3, bb: {b: 2}}},
c: {c: {c: 2}, cc: 'ball', ccc: 5},
d: 1,
e: {e: {e: 2}, ee: 'car'}
};
console.log(nestedEvenSum(obj2));
Upvotes: 3