Search code examples
arraysalgorithmiterationsubtraction

How to navigate in an Array of strings left and right


I have an array of strings

var characters = ["Jim", "Anna", "Nick", "Chris", "Peter"];

my initial position is Jim[0]. if i type right i want to go to the next one In this case to "Anna". I can do this by adding one to the current index.

The thing is getting more tricky when i type left from the initial position?

So how can i go from Jim[0] -> Peter[4]?

Something that works is

Jim[0] - 1 + characters.length which equals to  0 - 1 + 5 = 4

and this is Peter. But this seems incorrect because i cannot do that in the case that the current value is Anna[1] and i want to go to Jim[0]. As 1 - 1 + 5 = 5


Solution

  • Something like this would work.

    var characters = ["Jim", "Anna", "Nick", "Chris", "Peter"];
    var index = 0; // Currently at Jim.
    var direction = -1; // 1 for right, -1 for left.
    
    // What's left of our current position?
    characters[(index + characters.length + direction) % characters.length]; // Peter!