I have the following code to add up all the sum of the numbers in the object:
const obj = {
a: 1,
b: 2,
c: [1,2,3,4, [5,6,7]],
d: {
e: 1,
f: 2,
}
}
function sum(obj) {
let res = 0;
for(let key in obj) {
const val = obj[key];
if(typeof val === 'object' && !Array.isArray(val)) {
res = res + sum(val);
}
if(Array.isArray(val)) {
res = res + flattenArray(val);
}
else {
//console.log(val)
res = res + val;
}
}
return res;
}
function flattenArray(arr) {
let sum = 0;
for(let i = 0; i<arr.length; i++) {
const item = arr[i];
if(!Array.isArray(item)) {
sum = sum + item;
} else {
sum = sum + flattenArray(item);
}
}
return sum; //34
}
sum(obj);
In this function, the sum returns 34[object Object]. So 34 is the correct answer, but I'm a little confused on why it has the string [object Object] here.
I went through my code and I see that at this line:
//console.log(val)
val is actually an object: { e: 1, f: 2 }. However, why was it not caught by this condition:
if(typeof val === 'object' && !Array.isArray(val)) and go also into the else condition?
if {} if {} else {}chain. Please focus on that.if {} else if {} else {}chain