1

In the process of learning Javascript. I have written a code which goes through an array and adds them to res array. It will also go through the nested arrays and add them element by element to res. I have used recursion for this. But after each nested array finishes I am getting a Circular added to res. Unable to find where the problem is.

var res = ["oldarray"];

function findthis(xar){
  for(let n=0; n<xar.length; n++) {
    if(xar[n] instanceof Array) {
      res.push(findthis(xar[n]));
    } else {
      res.push(xar[n]);
    }
  }
  return res;
}

var d = ["z", 9, 2, ["r", "r", ["X","X","X","X"], "r"], "f", "x"];

console.log(findthis(d));

output this gives. when it should be an array without the added [Circular]

['oldarray', 'z', 9, 2, 'r', 'r', 'X', 'X', 'X', 'X', [Circular], 'r', [Circular], 'f', 'x']
4
  • What is the output supposed to look like? Commented Apr 15, 2020 at 12:38
  • 1
    same as the output but without the [Circular] added. Commented Apr 15, 2020 at 12:40
  • then change res.push(findthis(xar[n])); to findthis(xar[n]); That's where you push the circular references. Commented Apr 15, 2020 at 12:43
  • Does this answer on SO help you define what [Circular] means, and why its getting printed for you? stackoverflow.com/questions/7923959/… Commented Apr 15, 2020 at 12:45

1 Answer 1

2

[Circular] is printed out when you try to print an array or an object that contains a reference to itself. Here, you're getting it because you push the result of findthis (which is res) into res itself. To fix this, just remove the call to push in that case:

function findthis(xar){
  for(let n=0; n<xar.length; n++) {
    if(xar[n] instanceof Array) {
      findthis(xar[n]); // Here! findthis already pushes to res, no need for another push
    } else {
      res.push(xar[n]);
    }
  }
  return res;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nailed it. That makes complete sense now that you point it out.

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.