Skip to content
Advertisement

Create N dimensional grid of points in JavaScript

I know there are similar questions out there (the closest one I found was this JavaScript; n-dimensional array creation) but most one them are in Python and even this one I found I tried to implement in my code and It didn’t work.

So I want to create a function createGrid(L,n) that take as parameters two arrays of same size, L and n. In these, L[i] would specify the size of the grid in dimension i and n[i] would specify the number of points in the same dimension (such as the spacing between points is L[i]/(n[i] – 1). For example, for two dimensions lets say I call “let grid = createGrid([10,10],[2,2])” then the function should return an n+1 dimension array like this: [[[0,0],[0,10]], [[10,0], [10,10]].

So If I want to access a point in the grid I could simply type, for example, grid[1][0], which will return the point [10,0].

In this moment I am hardcoding this for 3 dimensions like this:

JavaScript

But I want to extend this by any number of dimensions. I tried to recurse as shown at the question I linked in the beginning but it simply did not work, so I tweaked it a little bit and things got worse, I from that point I just started getting more and more confused. If you can, please help! And thanks a lot!

Advertisement

Answer

You can use a loop. It is a great way to solve this problem.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement