Reputation: 11661
I have a table. each cell defiend by x,y position. for example cell number one is start at 0,0 and so on...
I want to take this table and turn it into this array of [x,y,x,y,x,y....]
.
For example for this picture the expected result should be this arr
:
const arr = [0,0,200,0,400,0,0,200,200,200,400,200,0,400,200,400,400,400];
The problem is I have only this data to work with:
const cols = 3;
const tableWidth = 600;
const colHeight = 200;
const items = 9;
const cellWidth = tableWidth / cols;
So I try to do a function that over all the items and try to figure out the x and the y. but I have no clue how to do that in one for only.
const arr = [];
for (var i = 0; i < items; i++) {
const even = i % 2 === 0;
const x = ???;
const y = i * colHeight;
table.push(x,y);
}
console.log({ arr });
Upvotes: 1
Views: 95
Reputation: 8491
I suggest you to calculate the number of rows and then iterate over rows and columns using 2 for
loops - it will be more readable:
const cols = 3;
const tableWidth = 600;
const colHeight = 200;
const items = 9;
const cellWidth = tableWidth / cols;
const rows = items / cols;
const arr = [];
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const x = j * cellWidth;
const y = i * colHeight;
arr.push(x, y);
}
}
console.log(arr);
UPDATE: if you still want one for
loop, try the following approach:
const cols = 3;
const tableWidth = 600;
const colHeight = 200;
const items = 9;
const cellWidth = tableWidth / cols;
const arr = [];
for (let i = 0; i < items; i++) {
const col = i % cols;
const row = Math.floor(i * cols / items);
arr.push(col * cellWidth, row * colHeight);
}
console.log(arr);
Upvotes: 2