How do I go back to the 0 index of the array and continue iterating over the array?

  • 0
    There is an array arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
    The user enters the data that the function receives as an array, for example:
    ['F', 4]. This means that you need to return 'B' from array, since the count goes from the element 'F' itself and around the array.
    JavaScript Willow Young, Dec 8, 2020

  • 2 Answers
  • 0
    If in the logic you described, then

    Array.prototype.getElByVal = function([v, i]){
    let index = this.indexOf(v), key = index+i-1;
    if(this.length <= key){
    key = key - this.length;
    }
    return this[key];
    };

    var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];

    console.log( arr.getElByVal(['F',4]) ); // "B"
    console.log( arr.getElByVal(['G',1]) ); // "G"
    console.log( arr.getElByVal(['G',2]) ); // "A"
    console.log( arr.getElByVal(['B',2]) ); // "C"
    Anonymous

  • 0
    (position + increment)% array.length
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!