0

I'm trying to do a for loop on an array and be able to start that loop on a specific index and loop over the array x amount of times.

const array = ['c','d','e','f','g','a','b','c']

I want to loop 8 indexes starting at any index I wish. Example starting at array[4] (g) would return

'g','a','b','c','c','d','e','f'

This is what I've tried so far

const notes = ['c','d','e','f','g','a','b','c']

var res = []
for (var i = 4; i < notes.length; i++) {
res.push(notes[i])
}

console.log(res)
B. Ford
  • 47
  • 4
  • 4
    The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Dec 05 '18 at 04:38

3 Answers3

6

You can use modulo % operator.

    const getArray = (array, index) => {
      const result = [];
      const length = array.length;
      for (let i = 0; i < length; i++) {
        result.push(array[(index + i) % length]);
      }
      return result;
    };
ekta patel
  • 129
  • 3
0

Simple way.

var notes = ['c','d','e','f','g','a','b','c'];

function looparr(arr, start)
{
    var res = [], start = start || 0;
    for(var index = start, length=arr.length; index<length; index++)
    {
        res.push(arr[index]);
        index == (arr.length-1) && (index=-1,length=start);
    }
    return res;
}

console.log(looparr(['c','d','e','f','g','a','b','c'], 0));
console.log(looparr(['c','d','e','f','g','a','b','c'], 2));
console.log(looparr(['c','d','e','f','g','a','b','c'], 4));
console.log(looparr(['c','d','e','f','g','a','b','c']));
Vignesh Raja
  • 7,927
  • 1
  • 33
  • 42
0

Very simple solution below :) While i < index, remove the first character from the array, store it in a variable and then add it back onto the end of the array.

let array = ['c','d','e','f','g','a','b','c'];
var index = 4;

    for(var i = 0; i < index; i++) {
        var letter1 = array.shift(i); // Remove from the start of the array
        array.push(letter1); // Add the value to the end of the array
    }

console.log(array);

Enjoy :)

Spangle
  • 762
  • 1
  • 5
  • 14