0

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));

1
  • 2
    You need replace Formation(obj[ky],sum); with sum += Formation(obj[ky],sum); Commented Apr 20, 2022 at 9:46

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.