1

I have a data where the key count appears 6 times and it is nested. I'm trying count the number of times it appears with below logic but somewhat I'm close to it not got the exact result.

The problem is child values I'm getting as 7 which I have consoled. but the final count is always 1 seriously I don't know why I'm getting 1. Any help!

let data = [{ "id": "1", "child": [ { "id": "12", "child": [ { "id": "123", "child": [ { "id": "1234" } ] } ] }, { "id": "2", "child": [ { "id": "22" } ] }, { "id": "3" }, { "id": "4", "child": [ { "id": "42", "child": [ { "id": "43" } ] } ] } ] }] const countChild = (arr,cnt = 0) => { for (const {child} of arr) { cnt = cnt + 1 console.log("child",cnt) if(child) countChild(child, cnt) } return cnt; }; console.log("Final count",countChild(data))

1
  • In your code cnt is in local scope so and as you are using recursion its keeping the cnt values associated with its context, so when its emptying the call stack the cnt value is 1, you need to put the cnt in global scope o JS wont make the local copies Commented Nov 3, 2022 at 9:40

3 Answers 3

2

I would recommend a reduce function for that:

const countData = (arr: any) => { return arr.reduce((results: number, elm: any) => { if (!!elm.child) { results += (1 + countData(elm.child)); } return results; }, 0); }; 

But if you still want to use your function, it needs to be adapted as below:

const countChild = (arr,cnt = 0) => { for (const {child} of arr) { if (child) cnt = 1 + countChild(child, cnt); console.log("child",cnt) } return cnt; }; 
Sign up to request clarification or add additional context in comments.

1 Comment

yes, but why my code is not working what's the problem. why it is returning 1?
2

you can do something like this

let data = [{ "id": "1", "child": [ { "id": "12", "child": [ { "id": "123", "child": [ { "id": "1234" } ] } ] }, { "id": "2", "child": [ { "id": "22" } ] }, { "id": "3" }, { "id": "4", "child": [ { "id": "42", "child": [ { "id": "43" } ] } ] } ] }] const flatChild = (arr) => arr.flatMap(({id, child}) => [id, ...flatChild(child || [])] ) const countChild = arr => flatChild(arr).length console.log("Final count", countChild(data))

Comments

0

let data = [{ "id": "1", "child": [ { "id": "12", "child": [ { "id": "123", "child": [ { "id": "1234" } ] } ] }, { "id": "2", "child": [ { "id": "22" } ] }, { "id": "3" }, { "id": "4", "child": [ { "id": "42", "child": [ { "id": "43" } ] } ] } ] }]; let cnt = 0; const countChild = (arr) => { for (const {child} of arr) { cnt = cnt + 1; console.log("child",cnt); if(child) countChild(child); } return cnt; }; console.log("Final count",countChild(data));

here simply putting the cnt in global scope so the JS will not make local copies for each recursive function

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.