B. Ford
B. Ford

Reputation: 47

Start a for loop on specific index and loop for array length

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)

Upvotes: 0

Views: 1769

Answers (3)

Spangle
Spangle

Reputation: 822

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 :)

Upvotes: 0

Vignesh Raja
Vignesh Raja

Reputation: 8751

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']));

Upvotes: 0

ekta patel
ekta patel

Reputation: 129

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;
    };

Upvotes: 6

Related Questions