What is the procedure for generating an nxn matrix (array within an array) that is completely populated with zeroes?

I'm looking to create an array matrix with the following structure:

createMatrix(4);

// desired output:
[[0,0,0,0],
 [0,0,0,0],
 [0,0,0,0],
 [0,0,0,0]];

Here's my current solution :

function createMatrix (n) {
  var innerArr;
  var outerArr = [];

  for (var i=0; i<n; i++){
    innerArr = [];
    for (var j=0; j<n; j++) {
      innerArr.push(0);
    }
    outerArr.push(innerArr);
  }
}

console.log(outerArr);

Is there a more efficient approach to achieve this? The current method involves iterating nxn times, which may not be optimal for such a simple task.

Answer №1

Utilizing the ECMAScript 2015 function Array.prototype.fill():

Array(row_count).fill(Array(column_count).fill(0)).map(a => a.slice())

Breaking it down:

// Creating a sparse array with row_count "absent" items:
Array(row_count)
// Generating an array with column_count elements all set to 0:
                      Array(column_count).fill(0)
// Filling an array with row_count copies of the same identic array:
Array(row_count).fill(Array(column_count).fill(0))
// Making a shallow copy of the inner array:
Array(row_count).fill(Array(column_count).fill(0)).map(a => a.slice())

Performance?

It appears that the variant using Array.prototype.fill() performs better as the size of the matrix increases (in comparison to utilizing loops). This observation is based on results from Firefox browser performance tests. Your results may vary.

Answer №2

There are several ways you could approach this issue:

Using concat() and slice()

var numCols = 4;
var numRows = 4;

var innerArrSrc = [];
var outerArr = [];

for (var i = 0; i < numCols; i++) {
    innerArrSrc.push(0);
}

for (var j = 0; j < numRows; j++) {
    outerArr.push(innerArrSrc.concat()); // Another option is to use innerArrSrc.slice();
}

Array.prototype.concat() and Array.prototype.slice() both provide a shallow copy of the original array.

Representing as a one-dimensional array

Alternatively, you can represent your matrix as a one-dimensional array and create functions to access specific indexes based on row-column values:

var numRows = 4;
var numCols = 4;
var len = numRows * numCols;

var outerArr = [];

for (var i = 0; i < len; i++) {
    outerArr.push(0);
}

A function for accessing a specific index in the matrix represented this way might look like:

function getMatrixIndex(myMatrix, col, row, numCols) {

    var index = row * numCols + col;
    return myMatrix[index];
}

Utilizing Array.prototype.fill

If you want to make use of ES6 features, Array.prototype.fill could be helpful:

// Multi-dimensional
var numRows = 4;
var numCols = 4;

var outerArr = new Array(row_count).fill(new Array(column_count).fill(0)).map(a => a.slice());

// Or one-dimensional
var len = numRows * numCols;
var oneDim = new Array(row_count * column_count).fill(0);

Performance Testing with jsPerf

You can conduct tests using this jsPerf test to determine the fastest method. The tests were run on various browsers and platforms, including:

  • Firefox 42.0 32-bit on Windows NT 10.0 64-bit
  • Chrome 44.0.2403.130 32-bit on Windows NT 10.0 64-bit
  • Chrome 47.0.2526.73 32-bit on Windows NT 10.0 64-bit
  • Android Browser 42.0 (Gecko) on Android 6.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

The functionality of the function from the controller does not seem to be effective within the Angular directive

Hey everyone! I created a form using dynamic data and in the future, I will need to compile this form, fill it with data, and submit it. Here is how I built the form: <div> <form name="pageForm"> <div> <div class="form-group" ng-repe ...

Julia's Guide to Efficiently Mutating Type-Stable Arrays

Hello everyone! I am new to Julia and I hope you don't mind if my question seems basic. I have been working on a scientific program where I am dealing with multiple arrays that are type-stable and have a fixed dimensionality. These arrays are updated ...

Keeping extensive files/information on disk in order to alleviate browser memory usage in JavaScript

Currently, I am faced with a challenge involving the encryption of very large files. Unfortunately, my browser keeps crashing due to running out of memory while trying to handle these massive files. To address this issue, I am considering transferring som ...

Tips for sending a string array as a parameter to a function?

After declaring the following: char array_slave_1[128][128]; int array_length(char *a[]){ int i = 0; while(a[i] != NULL){ i++; } return i; } int x = array_length(array_slave_1); The output I receive is as follows: main.c:101 ...

Conceal an HTML column in jQuery by clicking a button with the help of link_to in Rails and H

I'm attempting to conceal an HTML column by clicking a button using the jQuery hide method. Here is the HTML code: %br.clear - @cards.each do |card| %div{class: "hide_#{card.id}"} <- included this to address the problem .existing-credit ...

The Mapbox map fails to display properly upon initial page load

When my Mapbox map loads, I am experiencing issues with it only rendering partially. It seems that adjusting the width of the browser or inspecting the page will cause the map to snap into place and display correctly. To demonstrate this problem, I created ...

Updating the Backbone.js model within a MySQL database

I am facing an issue with my model setup: var Car = Backbone.Model.extend({ url: "/save.php", defaults: { color: "red" } }); Upon document ready, I initialize a new instance of the model and save it: new volvo = new Car({color:"gree ...

Button-click scrolling is our featured feature!

One interesting feature on my website is a button (within a div-element) located in the bottom-right corner. I am now looking to enhance this by adding a jQuery function that enables the user to scroll down the page incrementally simply by clicking and hol ...

Is there a way to use the onclick event to open a link in the same window and tab?

I am facing a challenge with a webpage containing multiple divs. I am trying to extract data from my database and display it within specific divs on the page. Additionally, I want this information to be presented when clicking on a link taking me back to t ...

What is the process for capturing input values when the enter key is pressed?

Is there a way to submit a form on Enter key press without refreshing the page? Below is my code snippet: PHP code: <form action="profile/update_profile" method="post" id="business_name_data"> <input type="hidden" name="business_name" id="busi ...

Ways to stop an app from being built if the component prop types are not valid?

Example of PropTypes Implementation: import PropTypes from 'prop-types'; class Greeting extends React.Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); } } Greeting.propTypes = { name: PropTyp ...

Inspecting Facebook links

Currently working on a website and interested in incorporating a feature similar to what Facebook has. I'm referring to the link inspector, but I'm not entirely sure if that's its official name. Allow me to provide an example to clarify my r ...

Using Vuejs to iterate over nested data

I am looking to implement a nested v-for loop in Vuejs, but I am unsure about how to structure my Data and the v-for loop itself. My goal is to iterate through modifiers without having to specify modifiers1, modifiers2 individually. The idea is to have t ...

Automatically populate select boxes with values from a different source using PHP

I'm in the process of setting up automatic population for 2 select boxes on a website. When a user chooses a class, the second select box automatically displays the main specialization of that class. If the user selects Tank (for example), the third ...

What is the best way to return JSON data in a compressed (gzip) format to an Ajax Request using Java?

When sending compressed JSON in response to an Ajax request from my Java program, I understand that I need to set the Content-Encoding in the Response Header to gzip. However, are there any additional steps I should take? ...

Tips for configuring jQtree to initially display the tree structure from the HTML source

Up to this point, I have utilized jQuery TreeView for the navigation menus on my website. However, as the main navigation menu has grown significantly in size (40869 bytes out of 67054 bytes), I am seeking a way to streamline it by using AJAX calls to fetc ...

What is the reason for the 'admin' page not being displayed?

After reading the MEAN MACHINE Book and following the instructions on Routing Node applications [pg - 36], I encountered an issue. The express.Router()⁴⁸ functions as a mini application where you can define routes. Let's see an example by adding ...

What could be causing the 400 error in my $http.post request?

I am relatively new to working with MEAN stack and I have encountered an issue that I hope someone can help me with. I am trying to implement functionality where an email is sent to a contact upon clicking a send button. I am using the SendGrid Nodejs API ...

Replicating the functionality of ActionScript 3.0 / JavaScript DateTime in Java

I need to transfer DateTime capabilities from ActionScript 3.0 to Java/Android. I am considering Joda for this task, but I'm unsure if there are any implementations of the DateTime object that comply with ECMA-262 3rd Edition. Is there a more lightwei ...

What is the best way to retrieve the name value from a nested JSON object using PHP?

Data: {"location":{"name":"Tirana","region":"Tirane","country":"Albania","lat":41.33,"lon":19.82,"tz_id":"Europe/Tirane","localtime_epoch":1484543668,"localtime":"2017-01-16 5:14"},"current":{"last_updated_epoch":1484543668,"last_updated":"2017-01-16 05:1 ...