Saturday, 28 September 2013

Reach nested array item using recursion - javascript

Reach nested array item using recursion - javascript

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.

No comments:

Post a Comment