Search code examples
javascriptcounting

How to get index of column based on continuous sequence of values


I have this sequence of numbers

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

Each number represents a component on a page. Every 3 numbers comprises a page. The component indexing restarts on every page. So basically column-based indexing.

You could think of it as

0   1   2
3   4   5
6   7   8
9   10  11
12  13  14
15  16  17
18  19  20
21  22  23
24  25  26
27  28  29

where each row is a page, and each column is a component.

I need to identify based on only these numbers which page/row and which component/column the number is in. Page and component counts are 0-based.

I have managed to identify the index of the page/row using Math.floor(number / 3).

How can I identify the component?

For example, 20 would be component 2 on page 6, 10 would be component 1 on page 3, 27 would be component 0 on page 9.


Solution

  • Use modulus operator :

    var component = number % 3;