2

I'm trying to select Nth element from array using this function:

function nthArr(arr, index){
 if (index === 0)
 return arr[index];
 else nthArr(arr.slice(1), --index);
}
nthArr([1,2,3,4,5,6],3)

I would await that it returns 4, but instead I get 'undefined'.
How should I return correct value?

rnevius
27.2k10 gold badges60 silver badges86 bronze badges
asked Sep 11, 2015 at 19:44
3
  • 4
    Shouldn't there be a return somewhere after else? Commented Sep 11, 2015 at 19:46
  • 4
    Ummm... but why? Doesn't arr[index] work for all indices anyway? Commented Sep 11, 2015 at 19:46
  • @JohnBupit arrays[] are accessed by index Commented Sep 11, 2015 at 19:46

2 Answers 2

3

You are missing a return statement in the else branch.

if (index === 0)
 return arr[index];
else {
 return nthArr(arr.slice(1), --index); // Note the return
}
answered Sep 11, 2015 at 19:46
Sign up to request clarification or add additional context in comments.

1 Comment

exactly - my java habits :-)
2

You're missing a return statement...But why not just simplify the whole thing?

function nthArr(arr, index){
 return arr[index];
}
var result = document.getElementById('result');
result.textContent = nthArr([1,2,3,4,5,6], 3);
<span id="result"></span>

answered Sep 11, 2015 at 19:53

1 Comment

yes this is simpler, but I needed it for traversing list object

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.