What is the best way to generate a 3x3x3 blank matrix in JavaScript?

I am attempting to construct a 3*3*3 matrix where each element will hold a cube. Currently, all the cubes are arranged in a 1D matrix called all_cube. However, I need to organize them in a 3D matrix named cube[][][].

Below is the code for a more 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);
            }
        }

    }
}

Answer №1

An effective approach involves utilizing nested Array.from() along with its built-in mapping callback.

The issue arises from not creating any internal arrays and instead pushing all elements 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)

Answer №2

To achieve the desired output, it is necessary to generate an array for each level and then add it to the previous level's array.

function buildCubeStructure()
{
    const cubeArray = [];
    for(let i= -1; i<= 1; i++)
    {
        const planeArray = [];
        cubeArray.push(planeArray);
        for(let j= -1; j<= 1; j++)
        {
            const rowArray = [];
            planeArray.push(rowArray);
            for(let k= -1; k<= 1; k++)
            {
                const cubeMesh = new THREE.Mesh( geometryObject, materialObject );
                cubeMesh.translateX(i*5.5);
                cubeMesh.translateY(j*5.5);
                cubeMesh.translateZ(k*5.5);

                scene.add(cubeMesh);
                rowArray.push(cubeMesh);
            }
        }

    }
    return cubeArray;
}

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

// Necessary declarations for code execution
const geometryObject = 0;
const materialObject = 0;
const scene = { add() {} };
class Mesh 
{ 
    constructor() {}
    translateX(value) { this.x = value; }
    translateY(value) { this.y = value; }
    translateZ(value) { this.z = value; }
}
const THREE = { Mesh };

console.log(buildCubeStructure());

Answer №3

A matrix is essentially a collection of nested arrays with varying depths. While Javascript doesn't support true multidimensional arrays, it can achieve similar results by nesting arrays within each other.

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing UTC Time with AngularUI's UI-Date Datepicker

My issue lies with the datepicker using localized time instead of UTC when making calls to the backend. To handle this, I've created a function that adjusts the value before posting it to the server: function adjustDateForTimeOffset(dateToAdjust) ...

When scrolling, apply a CSS class to a div element once it becomes visible on the

I'm in the process of developing a timeline feature for my website, and I am facing an issue where the addClass function is being applied to all sections, even those that are not currently visible on the screen during scrolling. If you would like to ...

Schema for Monogo Database

My goal was to have a property that could give me the timestamp of when a specific task was created. I decided to add a timestamp property and set it to true, but now my code won't compile. The code is functioning perfectly fine without the timestamp ...

Guide to configuring a service worker to manage the main website path

My website is hosted at https://xxxxxx.com. I have set the scope of the service worker file sw.js to /, but it seems that the service worker is unable to control the page https://xxxxxx.com. However, it can control other pages like https://xxxxxx.com/, e ...

Pass the full path of the Dropzone file to the Rails controller

I'm currently working on extracting the complete file path from a dropped folder in Chrome's Dropzone. All file upload data is being transferred correctly, but I also need to capture the full path of the uploaded file. Despite my efforts, I&apos ...

The "require" keyword cannot be used in a Node-RED Function node

When working with a Node-RED Function Node, the first line I include is: var moment = require('moment-timezone'); I'm attempting to create a timezone accurate date/time stamp for sensor data. However, when this node runs, I encounter the fo ...

ISO format for the number of weeks in a month, considering weeks that cross over Thursday

I am looking for a precise number of weeks per month in accordance with the ISO standard. Instead of using JavaScript's Date, I am utilizing momentJS. According to the ISO date format, a month's week count is determined based on whether it cont ...

Utilize filters to apply a class to an element only if its index exists within

Is it possible to add a CSS class in AngularJs based on the row index's presence in an integer array ( $scope.AssociateCandidatesIndex) using filters? Any suggestions on how to accomplish this? <tr ng-show="true" class="{{ $index}}"> < ...

Applying a combination of shaders to a single 3D object in Three.js and WebGL: A step-by-step guide

I'm tinkering with WebGL and experimenting with a 3D object using Three.js. I'm wondering if it's possible to apply multiple shaders to a single 3D object for enhanced visual effects. Any insights or knowledge sharing on this would be greatl ...

Angular 10 does not fulfill promises as expected

In the Angular 10 project I'm working on, I encountered an issue while trying to call an API request asynchronously using promises. The code I wrote didn't seem to execute the API call as expected and kept exiting at the first line without progre ...

Can you explain how HTML and JavaScript work together in terms of execution order?

As a newcomer to JavaScript, I'm curious about the execution order of line1, line2, and line3 in my code. My initial assumption was that it would display the paragraph first (line 1), followed by the image (line 2), and then trigger a prompt. However ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

Having difficulty locating any content within the return element in JSX

I'm relatively new to React and JSX and currently working on creating a button that, when clicked, should trigger a dialog box to appear. Within this dialog box, there should be a table with three columns: name, status, and exception error, all repres ...

What is the most effective way to create a straightforward user interface in Node Js for the purpose of automation?

Currently, I am employing Selenium webdriver alongside Javascript and Node JS for automating test cases. My initial test case looks like this : var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder(). withCapabili ...

A React-based frontend solution designed exclusively for managing data structures and databases

Challenges with Product Management In my React App, the shop features products sourced solely from a JSON file as an external API, all managed on the frontend. Recently, I encountered a product with limited availability - only 20 pieces in stock. I am uns ...

The error message "Comparison between 'NoneType' and 'int' not possible in Django dynamically added forms" is indicating an issue with comparing instances of different data types

Currently in the process of developing a website using Django where users can input recipe details and save them. This involves allowing users to dynamically add form fields for ingredients and recipe steps. I've managed to implement functionality to ...

Improving the efficiency of checking roles in Discord.js

Currently in the process of developing a Discord verification bot which includes the functionality of verifying if a user has at least one role from each required category, and then generating a summary of their roles. The existing solution I have works ...

The issue with Jquery.Validate not functioning properly when trying to upload a file

I have integrated jQuery validation into my ASP.NET MVC project, and it is functioning correctly with textboxes. However, I am encountering an issue with file uploads. Below is the code snippet I am using: @model ffyazilim.Management.Model.Credential.Crea ...

Creating dynamically generated nested text inputs with individual v-model bindings upon the clicking of a button

As a newcomer to vuejs, I am attempting to create nested textboxes dynamically with the click of a button. For a clearer explanation, please refer to this jsfiddle link: https://jsfiddle.net/avi_02/qLqvbjvx/ Let's use an analogy to grasp the iss ...

Issue with utilizing addEventListener("load") in Firefox in conjunction with <iframe>

I've encountered an issue with my iframe when it is used as the target for a form. In all major browsers, except for Firefox, the iframe successfully removes the main element upon pressing the submit button. However, in Firefox, the main element is re ...