Creating an array of arrays in Javascript: A comprehensive guide

Can someone assist me in creating an array of arrays? I have a matrix calculator and I need to create the array of arrays ('smaller'). How can this be achieved? The functions create2Darray and calculateDet are working fine, so there is no issue with them. Any help would be greatly appreciated. I require an array containing these arrays (minors of the main matrix) for calculating their determinants and finding the inverse matrix. Here is the HTML:

<div id = "table4">
<div class = "calcHeader">Inverse Matrix [3x3]</div>
<form id = "row1"><!--first row-->
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
 </form>
 <form id = "row2"><<!--second row-->>
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
</form>
<form id = "row3"><<!--third row-->>
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
    <input type = "text" class = "det3"/>
</form>
<div class = "count" onclick="invertMat('det3')"><a href = "#">Calculate</a></div>
</div>

Javascript

function invertMat(matrixClass) {
    var matrix = create2Darray(matrixClass);
    var det = calculateDet(matrix);
    //alert(det);
    var invMat = new Array();
    for (var i = 0; i < matrix.length; i++) {
        invMat[i] = new Array();
        for (var j = 0; j< matrix.length; j++) {
            invMat[i][j] = 0;
        }
    }
    if (matrix.length == 2) {
        invMat[0][0] = 1 / det * matrix[1][1];
        invMat[1][0] = 1 / det * (-matrix[1][0]);
        invMat[0][1] = 1 / det * (-matrix[0][1]);
        invMat[1][1] = 1 / det * matrix[0][0];
        alert(invMat);
    } else if (matrix.length == 3) {
        //var smaller = new Array();//creating an empty array for a matrix minor
        for (var i = 0; i < matrix.length; i++) {
            var smaller = new Array(matrix.length - 1);
            for (h = 0; h < smaller.length; h++) {
                smaller[h] = new Array(matrix.length - 1);
            }
            for (a = 1; a < matrix.length; a++) {
                for (b = 0; b < matrix.length; b++) {
                    if (b <i) {
                        smaller[a - 1][b] = matrix[a][b];
                    } else if (b >i) {
                        smaller[a - 1][b - 1] = matrix[a][b];
                    }
                }
            }
        }
    }
}

Answer №1

Here is an example: Fiddle

const firstArray = new Array();

firstArray.push(1);
firstArray.push(2);

const secondArray = new Array();

secondArray.push(3);
secondArray.push(4);

const thirdArray = new Array();
thirdArray.push(firstArray);
thirdArray.push(secondArray);

console.log(thirdArray[0]);
console.log(thirdArray[1]);

Answer №2

Check out the live demonstration here

function generateTwoDimensionalArray(rows, columns, callback) {
    var array = [],
        defaultValueFunction = function(x, y) {},
        customFunction = callback || defaultValueFunction;
    for (var i = 0; i < rows; i++) {
        for (var j = 0, currentRow = []; j < columns; j++) {
             currentRow[j] = customFunction.call(window, i, j); 
        };
        array[i] = currentRow;
    };
    return array;
};


function displayTwoDimensionalArray(array) {
    document.body.innerHTML += "<p><b>Array:</b></p>";
    for (var i = 0, length = array.length; i < length; i++) {
        document.body.innerHTML += "<p><b>" + i + "</b>: " + array[i].join(" ") + "</p>";
    };
};

var matrixA = generateTwoDimensionalArray(10, 10, function(x, y) { return 0;}),
    matrixB = generateTwoDimensionalArray(10, 10, function(x, y) { return x + y;});
displayTwoDimensionalArray(matrixA);
displayTwoDimensionalArray(matrixB);

To use this function:

var matrix = generateTwoDimensionalArray(10, 10);

You can also define a custom initialization function that takes the index as a parameter. For example, if you want to initialize your matrix with 0 by default:

var customMatrix = generateTwoDimensionalArray(10, 10, function(x, y) { return 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

Dealing with encoding problems in Node.JS when parsing JSON data with UTF-

I have developed a small script that allows me to fetch keyword suggestions from the Google search API. One major issue I am facing is when the response contains special characters (such as à é ù etc.): my application returns unreadable keywords like: ...

"Utilizing Vue.js for frontend, this app utilizes axios from the client side, rather than

As a newcomer to the world of programming, I apologize if my question sounds basic. I currently have a setup where a Vue.js application is running on a Linux Red Hat server with Apache installed via XAMPP. Additionally, an ASP.NET Core 6 Web API applicatio ...

NodeJS JSONStream causing memory exhaustion issue

I've encountered an issue while trying to stream a large JSON file (94mb in size) from an HTTP request to a local file using the JSONStream library in NodeJS. Despite setting a memory flag of 256mb with node --max-old-space-size=256 .\main.js, th ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

Efficiently uploading images with AJAX when submitting a form

I am attempting to upload an image along with other variables in a form submission, and then execute my PHP code to store the image in the user's profile_picture table. I want the image upload to be integrated within the same form used for saving dat ...

Sending a JSON stringified JavaScript object to a server: A step-by-step guide

I am currently working with VB.Net and MVC 5. In my project, I have an object that I created using javaScript: var myEdits = { listOfIDs: [], listOfValues : [] }; My goal is to send this object to the controller an ...

The NPM version needs to be updated as it is outdated

Struggling with a dilemma here. My Laravel project is quite dated, and I'm unable to execute npm run dev. Let's take a look at some code: php artisan laravel --version: Laravel Framework 5.8.38 node --version: v16.16.0 This is the current Node v ...

Arranging divs using inline-block display. How to adjust the heights consecutively?

After much searching and attempting, I am still unable to achieve a simple task. My goal is to apply display inline-block to some divs while aligning them in a row, similar to the image below: The issue arises when number 4 and 5 are positioned after 1 wi ...

Simplify an array in Javascript

I have a collection of objects structured in the following way: let list = [ { 'items': [ 'item 1', 'item 2' ] }, { 'items': [ 'item 3' ] } ] My goal is to flatte ...

Building React Typescript Components with Froala Editor Plugins

Attempting to integrate a custom plugin into a Froala Editor within my React application using the package react-froala-wysiwyg. Following a tutorial on incorporating a custom popup/plugin found here. Encountering an issue due to TypeScript incompatibility ...

Using jQuery, implement a functionality where a line break is added when the Enter key is pressed. Furthermore, the added

I have a text box where users can add cars to a list. Each car is entered on a new line, and when the user presses enter, jQuery adds a \n to move to the next line. However, when I collect this string, the \n characters are "hidden" and cannot b ...

Utilizing child component HTTP responses within a parent component in Angular: a comprehensive guide

As a newcomer to Angular, I find myself struggling with http requests in my application. The issue arises when I have component A responsible for retrieving a list of IDs that need to be accessed by multiple other components. In component B, I attempted t ...

What methods can be used to center a Google map on a specific location?

I am facing an issue with three map canvases on different divs. Despite setting the center to the same position in all three of them using JavaScript, the second and third maps do not seem to reflect that center. Does anyone have any insights on what cou ...

Ways to conceal images until AFTER the completion of the jquery flexslider loading process

After trying to integrate wootheme's Flexslider on my website, I encountered a small issue with its loading process. Whenever the page is refreshed with the slider, there is a brief moment (approximately 1 second) where the first slide appears overly ...

Is there a way to execute publish without automatically triggering postpublish?

I am working on a project that includes a specific postpublish action in its package.json. Recently, I encountered a situation where I need to run the publish command without triggering the associated postpublish action. Is there a foolproof method to exe ...

Navigating with Buttons using React Router

Header: I need help figuring out how to properly redirect to a new page when clicking on a Material UI button using the onClick method. Specifically, I am unsure of what to include in my handleClickSignIn function. Here is a snippet of code from my Header ...

Retrieve the content of a specific HTML tag using JavaScript

Is it possible to extract the content of a specific HTML tag as a string or XML format? <body> <script src="jquery.min.js"> //var test = document.getElementsByTagName("input"); //alert(test[0]); $(document).ready(function ( ...

JavaScript: Receiving an error that function is undefined when working with data binding

Why is my code showing that it's not defined while I'm attempting a simple code with data binding? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="ht ...

React JS's popup feature can be unreliable, as it tends to break the application frequently

I have been developing a web application that interacts with a public API and presents the retrieved data in a table format. However, I am encountering an issue where clicking the "Click to Display Hottest Planet" button sometimes results in an error. How ...

Programmatically setting properties for elements

I have a question about how to programmatically add a prop to a component in my React project. Here is the scenario: In the render() method, I have the following code snippet: <TextField name="password" va ...