DEV Community 👩‍💻👨‍💻

Erik Smith
Erik Smith

Posted on • Updated on

Modulo Around the Array

Typically in contemporary JavaScript we iterate over arrays with Array.map(), .reduce(), .forEach(), etc. These techniques assume we want to get through the entire array from start to finish all in one go. However, what if you have a slideshow that displays an array of images one at a time, and upon reaching the last image, you want to start over at the first?

For this sort of behavior, we can leverage the Remainder operator to automatically loop around the array to infinity. The for loop below makes it a little easier to visualize how this works.

const numRuns = 11;
const arr = ['a', 'b', 'c', 'd', 'e'];

for (i = 0; i < numRuns; i++) {
  const m = i % arr.length;
  console.log(`${i} % ${arr.length} = ${m}, arr[${m}] = ${arr[m]}`);  
}
Enter fullscreen mode Exit fullscreen mode
0 % 5 = 0, arr[0] = a
1 % 5 = 1, arr[1] = b
2 % 5 = 2, arr[2] = c
3 % 5 = 3, arr[3] = d
4 % 5 = 4, arr[4] = e
5 % 5 = 0, arr[0] = a
6 % 5 = 1, arr[1] = b
7 % 5 = 2, arr[2] = c
8 % 5 = 3, arr[3] = d
9 % 5 = 4, arr[4] = e
10 % 5 = 0, arr[0] = a
Enter fullscreen mode Exit fullscreen mode

Demo here https://replit.com/@365Erik/ModuloAroundTheArray.

Top comments (0)

You can see total article reactions, views, and listing information by heading over to your dashboard.