how to create 3*3*3 empty matrix in java script

Viewed 124

I am trying to create a 3*3*3 matrix in which each element will contain a cube. Currently, all the cubes are in a 1D matrix all_cube. But I need to create the same in matrix cube[][][].

Please find below the code for detailed explanation:

function createCubie()
{
    all_cube=[];
    for(var i= -1;i<=1;i++)
    {
        for(var j= -1;j<=1;j++)
        {
            for(var k= -1;k<=1;k++)
            {
                var cube = new THREE.Mesh( geometry, material );
                cube.translateX(i*5.5);
                cube.translateY(j*5.5);
                cube.translateZ(k*5.5);

                scene.add( cube );
                all_cube.push(cube);
            }
        }

    }
}
3 Answers

A convenient way is use nested Array.from() and it's built in mapping callback.

Your problem is you are not creating any of the internal arrays and are pushing everything into a single flat array

const arr = Array.from({length:3}, (_, i) => {
    return Array.from({length:3}, (_, j) => `row ${i}, elem ${j}`)
});


console.log(arr)

You need to make an array at each level and push it into the array from the previous level.

function createCubie()
{
    const all_cube=[];
    for(let i= -1;i<=1;i++)
    {
        const plane = [];
        all_cube.push(plane);
        for(let j= -1;j<=1;j++)
        {
            const row = [];
            plane.push(row);
            for(let k= -1;k<=1;k++)
            {
                const cube = new THREE.Mesh( geometry, material );
                cube.translateX(i*5.5);
                cube.translateY(j*5.5);
                cube.translateZ(k*5.5);

                scene.add( cube );
                row.push(cube);
            }
        }

    }
    return all_cube;
}

// ---- ignore below this line ----

// something so the code runs
const geometry = 0;
const material = 0;
const scene = { add() {} };
class Mesh { 
  constructor() {}
  translateX(v) { this.x = v; }
  translateY(v) { this.y = v; }
  translateZ(v) { this.z = v; }
}
const THREE = { Mesh };

console.log(createCubie());

A matrix is simply just an n-depth set of nested arrays. Javascript does not have the capacity to create multidimensional arrays, but can create n-dimensionally nested ones eg.

let cube = [[["x1"],["x2"],["x3"]],[["y1"],["y2"],["y3"]],[["z1"],["z2"],["z3"]]];

console.log(cube[0][0][0]);

Related