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:

let create3DSquareGrid = function(L, n){
    //L should be an array [Lx, Ly, Lz], if not they are all the same
    if(!Array.isArray(L)){
        L = [L,L,L];
    }
    //n should be an array [nx, ny, nz], if not they are all the same
    if(!Array.isArray(n)){
        n = [n,n,n];
    }
    //calculate the dl of each dimension
    var dl = L.map((val,i)=> Math.round(val/(n[i]-1)));
    
    //create the grid
    let grid = []
    for(let i=0; i<n[0]; i++){
        let x = i*dl[0];
        let gridJ = [];
        for(let j=0; j<n[1]; j++){
            let y = j*dl[1];
            let gridK = [];
            for(let k=0; k<n[2]; k++){
                let z = k*dl[2];
                gridK.push([x,y,z]);
            }
            gridJ.push(gridK)
        }
        grid.push(gridJ);
    }
    return grid;
}

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.

function createGrid(L, n) {
    var ans = L
    for (i = 1; i < L.length; i++) {
        var tmp = []
        for (el of ans) {
            innerTmp = []
            for (j = 0; j < L.length; j++) {
                innerTmp.push([el, L[j]])
            }
            tmp.push(innerTmp)
        }
        ans = tmp
    }
    return ans
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement