I'm trying to reach the center of a nested array using recursion. This is part of a larger problem I'm trying to solve. I'm sure the solution is somewhat elementary. I've been learning JS/web dev and am stumped.
Here's my code:
var j = [[[["hey!"]]]];
function getNested(obj) {
for (var i = 0; i < obj.length; i++) {
if (Array.isArray(obj[i])) {
obj = obj[i];
getNested(obj);
}
return obj[i];
}
}
The function is supposed to return the 'hey!' string, but I can't seem to get it right.
2 Answers 2
You are close, just switch out the findType(obj) for return getNested(obj[i]). This will give you a recursive function that drills down into the array until the item in the array is not another array. Also, the for-loop was unnecessary, given your example input.
This will only work if your nested arrays have exactly one element. Others have expressed this in the comments.
var j = [[[["hey!"]]]];
function getNested(obj) {
if (Array.isArray(obj)) {
return getNested(obj[0]);
}
return obj;
}
var str = getNested(j);
console.log(str); // "hey!"
Comments
There is no need for recursion, a simple while loop will already do the trick
var j = [[[["hey!"]]]];
function getNested(obj) {
while (Array.isArray(obj)) { obj = obj[0]; }
return obj;
}
var str = getNested(j);
console.log(str); // "hey!"
The recursive implementation has the nice property that it is purely functional though if you rewrite it like so:
var j = [[[["hey!"]]]];
function getNested(obj) {
return Array.isArray(obj)? getNested(obj[0]): obj;
}
var str = getNested(j);
console.log(str); // "hey!"
Still its performance would be worse though.
forloop if you'll only ever find the first innermost nested element and return it? How is your code recursive?getNestedcalls itself, be it directly or through mutual recursion.findType? If you're looking for recursion, switch out that line forreturn getNested(obj)