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']
res.push(findthis(xar[n]));tofindthis(xar[n]);That's where you push the circular references.