fucntion to loop variable length array either left or right in batches of 6 in javascript

To loop through an array left or right, in batches of 6, we can create a function in JavaScript that takes in the array as an argument and the direction we want to move as a string: "left" or "right".

In this function, we can check the direction and then use a while loop to iterate through the array in batches of 6. We can slice the array, move the items to the left or right by 6 indexes, and then concatenate the result back into the original array.

Here is the code:

index.tsx
function loopArrayInBatch(arr, direction) {
  let batchSize = 6;
  let startIndex = 0;
  let tempArr = arr.slice();

  if (direction === "left") {
    while (startIndex < tempArr.length) {
      let endIndex = startIndex + batchSize > tempArr.length ? tempArr.length : startIndex + batchSize;
      let slicedArr = tempArr.slice(startIndex, endIndex);
      tempArr = tempArr.concat(slicedArr);
      tempArr.splice(startIndex, batchSize);
      startIndex += batchSize;
    }
  }

  if (direction === "right") {
    while (startIndex < tempArr.length) {
      let endIndex = startIndex + batchSize > tempArr.length ? tempArr.length : startIndex + batchSize;
      let slicedArr = tempArr.slice(startIndex, endIndex);
      tempArr.splice(startIndex, batchSize);
      tempArr = slicedArr.concat(tempArr);
      startIndex += batchSize;
    }
  }

  return tempArr;
}
868 chars
28 lines

To use this function, we just need to pass in the array we want to loop through and the direction we want to move in batches of 6:

index.tsx
let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

// move to the left in batches of 6
let leftArray = loopArrayInBatch(myArray, "left");
console.log(leftArray);

// move to the right in batches of 6
let rightArray = loopArrayInBatch(myArray, "right");
console.log(rightArray);
295 chars
10 lines

This function should correctly loop through an array in batches of 6, either to the left or the right.

gistlibby LogSnag