Modulo-based Array Iteration

Found a neat algorithm for iterating through an array using modulo indexes

| reddiedev Modulo-based Array Iteration

Iterating through an array

With most of my projects, I usually find myself needing to iterate through an array of objects or items and having a way to paginate them. For example, in DiscordJS, I have to paginate between multiple “pages” of a message - such as having multiple pages for a leaderboard ranking system.

const data = ["a","b","c"];

let currentIndex = 0;
let currentPage = data[currentIndex];

// some logic for going to the next page
goToNextPage(){
    currentIndex += 1;
    currentPage = data[currentIndex];
} 

Using this format, there would be cases wherein I would exceed the size of the data array, so there was a checker in place to reset the current index to 0 whenever we reach the limit

goToNextPage(){
    currentIndex += 1;
    if (currentIndex == data.length) currentIndex = 0;
    currentPage = data[currentIndex];
}

goToPreviousPage(){
    currentIndex -= 1;
    if (currentIndex == 0) currentIndex = data.length - 1;
    currentPage = data[currentIndex];
}

Elegent way of Iterating through an array

This has worked well for me in the past and I haven’t had problems using it. The logic also makes sense whenever we have to go back to the previous page

Recently, however, I came across a video from Hyperplexed that shows an elegant way of doing the process I described above.

goToNextPage(){
    currentIndex += 1;
    currentPage = data[currentIndex % data.length];
}

It uses a modulo operation instead to make sure that the current index stays within the bounds of the array length. When I first saw this, I experienced a wave of amazement in how programming and logic still surprises me to this day. I definitely have a small but significant passion for ensuring that my algorithms stay as optimized as possible, and I will definitely be using this method in the future for iterating through an array.