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

I have an inquiry regarding the live method

$('.classname').live('click',function() { some code; }); Would there be any performance issues if there are around 100 to 300 elements with this specific class? ...

Steps for removing the console warning message: "The use of enableRowSelect has been deprecated. Instead, please utilize rowSelection."

) I have integrated React Data Grid from https://adazzle.github.io/react-data-grid/ multiple times in my application. One thing I noticed is that there is a console warning related to a prop called "enableRowSelect" which indicates whether the prop is bein ...

PHP Boolean Arrays: Exploring the Power of Booleans

I'm struggling with a conditional array in PHP and need some help. Below is my code snippet: foreach($orders as $order) { array_push($list, array($order['name'],$order['email'],$order['buyer_accepts_marketing'])); } So ...

It is imperative that the HTML div element remains within the boundaries of the page

Let me begin by providing some context. I am currently developing a responsive page that uses percentages to position my divs, allowing users to drag and drop items wherever they please. However, a problem arises when the user positions an object too close ...

Dynamic Field Validation in Angular 6: Ensuring Data Integrity for Dynamic Input Fields

After successfully implementing validation for one field in my reactive form, I encountered an issue with validating dynamically added input fields. My goal is to make both input fields required for every row. The challenge seems to be accessing the forma ...

The onWrite cloud function does not activate upon the creation of a new document

I have a collection called 'Users' that stores documents with user objects as well as a sub-collection named 'Notifications'. When a new notification is generated for a user, a corresponding document is created in the 'Notification ...

Trouble with ScrollTo animation on div with adjustable offset top feature - seeking assistance

Having trouble navigating to the correct slide when clicking the right button on the navigation menu. Clicking the menu button displays a list of links. Clicking on a link for the first time will take you to the correct slide, but if you try clicking a dif ...

The error prop in Material UI DatePicker does not function properly when combined with yup and react-hook-form

Currently, I am working on enhancing a registration form using tools such as yup, react-hook-form, and Material UI DatePicker/TextField. My goal is to include a date of birth field that validates whether the user is over 18 years old. Although the error me ...

Unable to modify the .top attribute style in elements within an arraylist using JavaScript

I need to align multiple images in DIVs on the same line by setting their Top value to match the first image in the array. Here is the code I am struggling with: (addBorder function is called when divs are clicked) <div class="DRAGGABLE ui-widget-cont ...

Error: The default export is not a component compatible with React in the specified page: "/"

I'm facing an issue while building my next app. Despite using export default, I keep encountering an error that others have mentioned as well. My aim is to create a wrapper for my pages in order to incorporate elements like navigation and footer. vi ...

What steps should I take to make sure the vuex store is included in my build process?

I am currently working on a Vue application using vue cli 3. I found a guide here that explains how to build the app with vue-cli-service build --target wc --name my-element [entry] In order to test the output, I have created an index.html file: <!D ...

Guide on using Fetch API to send a request to a PHP file using the POST method

Hey everyone, I've recently started delving into the world of PHP and I encountered an issue while attempting to send a post request from my JavaScript file to my PHP file using the Fetch API. Upon making the request in my console, I received the foll ...

Switching up the image using a dropdown selection menu

I am struggling with updating an image based on the selection made in a dropdown menu. I am quite new to javascript, so I believe there might be a simple issue that I am overlooking. Here is my attempt at doing this: JS: <script type="text/javascript" ...

Convert XML to an HTML table in real-time as new elements are introduced

Currently, I have JSON and AJAX code that fetches XML data every second, which is working smoothly. When I added an XML element, it automatically gets added to an HTML table. The issue arises when I call the function every 3 seconds; the page refreshes due ...

Tips for dynamically updating an input within a shadow DOM using code?

Snippet: https://jsfiddle.net/5zrwdjy7/2/ I'm currently working on automating keystrokes with a script within Cypress, however, the target website I am dealing with utilizes web components as inputs. These input elements are nested inside what is kno ...

Troubleshooting KuCoin API: Dealing with Invalid KC-API-SIGN Error and FAQs on Creating the Correct Signature

I want to retrieve open orders for my account using the following code snippet: import { KEY, PASSWORD, SECRET } from "./secrets.js"; import CryptoJS from "crypto-js"; const baseUrl = 'https://api.kucoin.com' const endPointOr ...

updating the HTML DOM elements using JavaScript is not yielding any response

One way that I am trying to change the background of a div is by using a function. Below is an example of the html code I am working with: $scope.Background = 'img/seg5en.png'; document.getElementById("Bstyle").style.background = "url("+$scope.B ...

Refresh the information on the page by loading data from the log file using AJAX

I am currently running a shell script in the background and directing the output to a log file using PHP. I'd like to showcase the content of this log file on the webpage, which I've managed to achieve with the following code snippet. <?php ...

Display all files within every subdirectory located in a specified folder on Google Drive

Recently, I stumbled upon a script located at https://github.com/bluexm/snipets/blob/master/list%20Gdrive%20files%20and%20folders. The challenge I encountered was that the script was not capable of handling folders with identical names. As a result, I made ...

Utilizing Google App Engine for seamless deployment, integrating Ajax for dynamic interactions, and

Using the google App Engine, I am looking to implement javascript (or Ajax) for POSTing a form and updating the target div. The form includes multiple fields and files for transfer. The javascript function I am using is extracted from the "Javascript: The ...