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

3 Answers 3

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;
    };
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.