Search code examples
javascriptgrid-layoutmodulo

Use mod to calculate which row was tapped in?


This is more of a math problem really. I have a 3 column grid and am trying to determine which row a tap was in.

I just can't quite work out the math so that a tap of item 0,1,2 will output 0 and a tap of 3,4,6 will output a 1 etc. Any ideas for how to do this calculation?

Row0 = items 0, 1, 2
Row1 = items 3, 4, 5
Row2 = items 6, 7 ,8

Many thanks!


Solution

  • You're just looking for division, not modulus or remainder:

    var row = Math.floor(x / 3);
    

    Example:

    var i, row;
    for (i = 0; i < 9; ++i) {
      row = Math.floor(i / 3);
      console.log(i + " => " + row);
    }
    .as-console-wrapper {
      max-height: 100% !important;
    }