0

I'd like to create an coordinates array so that I don't have to manually write 100 pairs of x and y values. I was thinking of using for loop inside another for loop, but I couldn't achieve it.

I'd like to make an empty array, named CoordsArray, and making use of the push method within the most inner for, create an mixed array as follows:

var coordsArray = [
{x:0,y:0},{x:0,y:20},{x:0,y:40},{x:20,y:0},{x:20,y:20},{x:20,y:40},{x:40,y:0},{x:40,y:20},{x:40,y:40}
]

The usage of the above code is for creating three rows of three circles (using D3js) without creating the array manually, because later I'll have to create a 10 rows of ten circles and creating the x and the y position of each one will be very cumbersome. What's the best approach to achieve it? Thanks.

Julio Rodriguez
  • 499
  • 6
  • 16
  • See also https://stackoverflow.com/questions/45813439/itertools-combinations-in-javascript, https://stackoverflow.com/questions/8936610/how-can-i-create-every-combination-possible-for-the-contents-of-two-arrays – i alarmed alien Sep 13 '18 at 14:42
  • you are right, I was meant to say {x:0,y:0} .. etc. Thanks – Julio Rodriguez Sep 13 '18 at 17:04

2 Answers2

2

The pattern I see is this:

  • the x-value is the (array index / # of cols) rounded down to the nearest integer
  • the y-value is the modulo of the (array index / # of cols)

So you can start with an empty array of length (rows * cols), fill each entry with the circle size, and then map each element to an object created by multiplying the array value by those x and y calculations...

let rows = 3,
    cols = 5,
    size = 20;

let data = new Array(rows*cols)
    .fill(size)
    .map((d, i) => ({
        x: d * Math.floor(i/cols),
        y: d * (i%cols)
    }));

console.log(data);

Granted, it may not be as human-readable as nested loops, but I like it...

SteveR
  • 1,015
  • 8
  • 12
0

You should always post the code you've tried.

Here's one way:

var coordsArray = [];

const rows = 10,
  cols = 10,
  size = 20;

for (var row = 0; row < rows; row++) {
  for (var col = 0; col < cols; col++) {
    coordsArray[row * cols + col] = [row * size, col * size];
  }
}