Finding value of each member of a column in grid (JS)

377 views Asked by At

I am having a bit of an issue and hoping someone can help. I am only a beginner at JS so this might have a really simple answer that is going over my head.

I have a grid that can be dynamically created based on user specified rows and columns. I have an array of row numbers and an array of col numbers and attributed an ID to each member using this formula:

index = (maxcols * rownumber) + col;

I have then added an ID to each member of the grid, resulting to something like this:

1   2   3
4   5   6 
7   8   9 

Basically what I am trying to find is the value of every member of a column and add that to its own array. So in this case the answer might be

column1 [1,4,7];
column2 [2,5,8];
column3 [3,6,9];

The result im going for is to allow me to find the relative column just by having the member ID. Any push in the right direction would be fantastic. Thanks in advance!

2

There are 2 answers

0
nobe4 On

If I understand correctly, you can do this:

var maxcol = 4,
    maxline = 4,
    col = 2,
    line = 3;

var index = (maxcol * line) + col;

var foundCol = index % maxcol; // found the column
var foundLine = (index - col) / maxline; // found the line

console.log(index, foundCol, foundLine);

Then loop through all indexes and add to the columnsValues[foundCol] your value.

Does this help ?

0
skazska On

Answer to your qquestion could heavy depend on way you access members of grid and its framework.

If not talking about any DOM related aspects, like assigning column ids to grid member elements in attributes, or event handlers paramaters, you could try to encode colid in member id. Again, if you refuse characters in member ids, you can encode it by fraction:

1.1 2.2 3.3
4.1 5.2 6.3
7.1 8.2 7.3  

index = (maxcols * rownumber) + col + col/10;

or

1.001 1.002 1.003
2.001 2.002 2.003
3.001 3.002 3.003  

index = row + col/1000;

or even

1.5 1.(3) 1.25
2.5 2.(3) 2.25
2.5 2.(3) 2.25

index = row + 1/(col+1);

or digit rank (encoding both col and row with limitation of <100 cols):

101 102 103
201 202 203
301 302 303

index = 100*row + col;