1

Just as a curiosity, Is it possible to return an element of an array during recursive iteration?

var index = 0;
function iterArray(arr){
    if(arr && index <= arr.length ){
        console.log(arr[index]); //Wanted to return this value instead calling any function here
        index++
        iterArray(arr)
    }
}

NOTE :- Above code will not execute as I expect., But I want that it should work sort of arr.pop. Like:

k = ["a", "b", "c"];
ret1 = iterArray(k);
ret2 = iterArray(k);
ret3 = iterArray(k);
console.log(ret1, ret2, ret3)//"a", "b", "c"
5
  • 3
    return (arr[index]); maybe...? Commented Oct 26, 2015 at 11:01
  • What is the desired ret value and function logic? Commented Oct 26, 2015 at 11:04
  • @kriggs - what about remaining code, would it execute? Commented Oct 26, 2015 at 11:04
  • Code placed after the return will not execute. Commented Oct 26, 2015 at 11:06
  • @Andrey - Sorry, I was wrong, Please check updated the code Commented Oct 26, 2015 at 11:06

4 Answers 4

1

Array.pop doesn't need recursive implementation.

But if it's general question - I'd think of some ECMAScript 6 generators.

function* iterArray(arr, idx) {
  yield arr[idx];
  yield* iterArray(arr, ++idx);
}

var arr = [1,2,3];

var g = iterArray (arr, 0);
console.log(g.next().value);
console.log(g.next().value);
console.log(g.next().value);

It's easy with generators, but to do similar things in ES5 environment - you'll need to transpile this code, or implement similar mechanism manually.

P.S: I used babel for transpilation.

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

1 Comment

This is what I was looking for. Thank you
1

This function may be use for searching exist key in array

function iterArray(arr){
    if(arr instanceof Array && arr.length) {        
        return arr.shift();        
    };  
}


k = ["a", "b", "c"];
ret1 = iterArray(k);
ret2 = iterArray(k);
ret3 = iterArray(k);
console.log('ret1 '+ ret1 + ' ret2 '+ ret2 + ' ret3 ' + ret3);

But, a function iterArray() changed a original array. Be carefully use this function

1 Comment

Thanks for help, but I'm looking this output by recursive iteration. There are many ways to do this as you shown.
1
Function recurseOverArrayLookingForValue(array, value, currentIndex){
if (currentIndex == undefined)
{ 
   currentIndex = 0;
}
if (currentIndex >= array.length)
{
    Return -1; //not found
}
if (array[currentIndex] == value){
    return currentIndex;
}
    RecurseOverArrayLookingForValue(array,value,currentIndex);
}

That will recursively iterate over an array and return a value that matches the input. You call it without defining the currentIndex and it will start at the beginning and recurse to the end or you can define it and recurse from there.

The thing about recursion is you have to have a predefined exit state that will cause the function to terminate execution. Otherwise you get an infinite loop, basically. So in your example, you need to define some reason to return the value in that index or otherwise continue to recurse until you hit the end of the the array at which point you should, again, exit the function - this is why I choose to add the look for a value logic. If you're not looking for a specific value then you need to define another reason to exit returning a given value. Maybe call another function that returns true ilor false based on whatever you need the number for or if it meets certain criteria. Otherwise your exit status will always be the end of the array.

Comments

0

I don't see the need of recursion here, if you want to return a function then re-run the function you can use setTimeout depending on the framework, will work just fine in browsers.

var index = 0;
function iterArray(arr, index){
    if(arr && index <= arr.length ){
        index++;
        setTimeout( fucntion(){iterArray(arr, index);^, 10 ); // Index is a global var, why you're passing it?
        return (arr[index]);
    }
}

This will continue the recursion but will return just the first match. To do what you're trying to accomplish by your example, the best way AFAIK is to mimic a class:

function nextIndexContainer( arrayToStore ){
   // Make a copy so it doesn't get changed on the fly, or remove the JSON's if this behaviour is desireable
   this.array = JSON.parse( JSON.stringify( arrayToStore ) ); 
   this.index = 0;

   this.next = function(){
      if( this.array[ this.index ] )
         return this.array[ this.index++ ];
      else
         return 'Last index reached';
   }
}

To use it:

var arrIndex = new nextIndexContainer([1, 5, 8]);
console.log(arrIndex.next()); // '1'
console.log(arrIndex.next()); // '5'
console.log(arrIndex.next()); // '8'
console.log(arrIndex.next()); // 'Last index reached'

Comments

Your Answer

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.