find the addition of nested object using recursion here my sum is always passed as 10 ??......... I am trying to add sum value in else condition but in if it always pass as 10
let abc = { a: 10, b: { a: 20 }, c: { b: { a: 30 } } };
const Formation = (obj,sum) =>{
for(let ky in obj) {
if (typeof obj[ky] == 'object') {
Formation(obj[ky],sum);
} else {
sum += obj[ky] ? obj[ky] : 0;
}
// console.log(sum)
}
return sum;
}
console.log('res: ', Formation(abc, 0));
jsN00b
3,7032 gold badges10 silver badges22 bronze badges
1 Answer 1
Yes, it's because you don't use returned value from nested Formation. You need make some changes to your code:
let abc = { a: 10, b: { a: 20 }, c: { b: { a: 30 } } };
const Formation = (obj) =>{
let sum = 0;
for(let ky in obj){
if(typeof obj[ky] == 'object'){
sum += Formation(obj[ky]);
}
else{
sum += obj[ky] ? obj[ky] : 0;
}
// console.log(sum)
}
return sum;
}
answered Apr 20, 2022 at 9:56
Alexander Paschenko
7615 silver badges12 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
Formation(obj[ky],sum);withsum += Formation(obj[ky],sum);