1

I have an array and i need to fetch elements from the array inside a loop. Let me explain,

var globalArray = ['apple','orange','melon','banana'],
    loopLimit = 5,
    fruitsPerLoop = 3;

for (var i=1; i<=loopLimit; i++) {
   // when the loop runs for the first time i need to grab the first 3 elements from the array since fruitsPerLoop is 3 and for the second time the next 3 (out of bound should be taken care) and for third time etc...
   //Pseudo with fruitsPerLoop as 3
   when i = 1 ==> globalArray should be ['apple','orange','melon'] 
        i = 2 ==> globalArray should be ['banana', 'apple','orange']
        i = 3 ==> globalArray should be ['melon','banana', 'apple']
        i = 4 ==> globalArray should be ['orange','melon','banana']
        i = 5 ==> globalArray should be ['apple','orange','melon']
}

I was referring underscore.js and trying to use some native methods as well but it breaks at some point.

Sai
  • 1,312
  • 2
  • 23
  • 41

1 Answers1

0

How about creating a recursive function to determine the index:-

var globalArray = ['apple', 'orange', 'melon', 'banana'],
  loopLimit = 5,
  fruitsPerLoop = 3;

function getIndex(i, minus) {
  var index = i - minus;
  if (index < 0)
    return getIndex(globalArray.length, minus - i)
  return globalArray[index];
}

for (var i = 1; i <= loopLimit; i++) {
  console.log([getIndex(1, i), getIndex(2, i), getIndex(3, i)])
}
BenG
  • 13,680
  • 4
  • 41
  • 57