Laxmikant
Laxmikant

Reputation: 2226

recursion return element of array

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"

Upvotes: 1

Views: 102

Answers (4)

Kriggs
Kriggs

Reputation: 3778

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'

Upvotes: 0

Batman
Batman

Reputation: 702

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.

Upvotes: 1

Andrey
Andrey

Reputation: 4050

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.

Upvotes: 1

Artem Chernov
Artem Chernov

Reputation: 906

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

Upvotes: 1

Related Questions