0

I have a simple function to get value from nested arrays:

function getVal(arr){
  var el = arr[0];
  console.log(el);
  console.log(Array.isArray(el));
  if(Array.isArray(el)){
    getVal(el);
  }else{
    return el;
  }
}

And I get undefined all the time. Here is the console output:

getVal([["a"]]);
["a"]
true
"a"
false
undefined

As far as I understand, when el === "a" condition if(Array.isArray(el)) is satisfied and I get recursive call with getVal("a"), which gives undefined result. What's happening there? And why "a" is not returned?

2

2 Answers 2

4

You haven't return the value from the recursive function call when Array.isArray(el) is true. Return it like return getVal(el);

function getVal(arr){
  var el = arr[0];
  if(Array.isArray(el)){
    return getVal(el);
  }else{
    return el;
  }
}

console.log(getVal([["a"]]));

Sign up to request clarification or add additional context in comments.

Comments

1

replace

getVal(el);

with

return getVal(el);

1 Comment

Thanks, that worked!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.