Tam2
Tam2

Reputation: 1367

Cycle through array after search

I'm trying to return the next item in a given array after performing a search to locate the index of a particular item.

I've got the below code which locates the index but it fails to return the next value

var myArray = [{"id" : "51fcd6fcf22d94c881000005","creator" : true}, 
               {"id" : "5244abaa0c11b3da22000012","creator" : false}, 
               {"id" : "52027f4354c8a8fd33000008","creator" : false}]

function nextElement(id) {
   var i = myArray.length;
    while( i-- ) {
        if(myArray[i].id == id) break;
     }
      console.log(i) <-- This returns '0' which is correct
      console.log(myArray[i++%myArray.length]); <-- This returns the object value at 0 too
};

nextElement('51fcd6fcf22d94c881000005')

What doesn't work is when I run the function it returns the object that I pass into the function

I want to be able to pass an ID into the function and return the next item, but if its the last item in the array then I want it to cycle and return the first one.

For example if the passed in ID was 52027f4354c8a8fd33000008 then I would want it to return the object at 0 i.e {"id" : "51fcd6fcf22d94c881000005","creator" : true}

Upvotes: 0

Views: 32

Answers (2)

Barmar
Barmar

Reputation: 782508

Change:

myArray[i++%myArray.length]

to:

myArray[++i%myArray.length]

The way to remember which is which is that if the ++ is before the variable, it increments before returning; if it's after the variable, it increments after saving the value to return.

Upvotes: 2

NPE
NPE

Reputation: 500893

Replace i++ with ++i. The former evaluates to the old value of i and then increments the variable.

Upvotes: 1

Related Questions