How can I get next few elements in an array but jump back to the start when passing the last element?

6

Imagine I have the following simple array:

const myArr = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"];

Now I want to get the next for instance 3 elements after "el5" (index 4). As you can see there are only 2 elements left in the array. When hitting last index in the array I want to go back to the start and continue there.

This should be the expected output when the start is "el5" (index 4): ["el6", "el7", "el1"].

And this is what I've tried so far.

const myArr = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"];
let output = [];

const followingElementsCount = 3;
let startIndex = myArr.findIndex(el => el === "el5") + 1;
let overflow = 0;
for (let i = 0; i < followingElementsCount; i++) {
  if (startIndex + i >= myArr.length) {
    startIndex = 0;
    overflow++;
  }

  output.push(myArr[startIndex + i + overflow]);
}

console.log(output);

I can't believe it but I'm not capable of solving this probably fairly simple problem.

Share
Improve this question

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue