Search code examples
arraysalgorithmmathgridformula

Grid how to find the index of the first position of the next row given a starting index


 0  1  2  3  4
 5  6  7  8  9
10 11 12 13 14

assume there is an array like a css grid with 15 elements like above, there are five columns and 3 rows, and starting index is 0

given the index of any element, how do you find the index of the first position that is in the next row ?

for example,

index 4 returns 5
index 6 returns 10
index 2 returns 5
index 11 returns 15
index 0 returns 5
index 14 returns 15

my formula is not working

const colPosition = index % colCount;
const rowPosition = Math.floor(index / colCount);
const answer = index + (colCount - colPosition) + 1;

Solution

  • const colPosition = index % colCount
    const rowPosition = Math.floor( (index - colPosition) / colCount)
    const answer = (rowPosition + 1) * colCount