What is the best way to populate a multidimensional array with zeros in JavaScript?

As I am delving into the world of JavaScript, I find myself struggling with manipulating multidimensional arrays.

var myarr = [ 
       [ 7, 9, 10 ], 
       [ 6, 9 ], 
       [ 5, 9 ] 
  ]

I am looking to insert a zero as shown below. Can anyone guide me on the most efficient way to accomplish this in JavaScript?

       [ 
           [ 7, 9, 10 ], 
           [ 6, 9, 0 ], 
           [ 5, 9, 0 ] 
       ]

Answer №1

One way to ensure all inner arrays have the same length is by first finding the max length of the arrays and then appending zeroes to shorter arrays until they match the max length.

var myarr = [[7, 9, 10], [6, 9], [5, 9]],
    length = myarr.reduce(function (r, a) { return Math.max(r, a.length); }, 0);

myarr.forEach(function (a) {
    while (a.length < length) {
        a.push(0);
    };
});

console.log(myarr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

var numbers = [ 
       [ 7, 9, 10 ], 
       [ 6, 9 ], 
       [ 5, 9 ] 
  ]

for(var j = 0; j < numbers.length; j++) {    
    if(numbers[j].length < numbers.length){
       numbers[j].push(0);
    }
}

console.log(numbers);

Answer №3

Check out this possible answer:

let array = [
  [4, 7, 9],
  [8, 5, 6, 3],
  [1, 2]
];

let rows = array.length;
let columns = 0;

for (let index in array) {
  if (array[index].length > columns)
    columns = array[index].length;
}

for (let i = 0; i < rows; i++) {
  for (let j = 0; j < columns; j++) {
    if (array[i][j] === undefined)
      array[i][j] = 0;
  }
}

console.log(array);

Answer №4

To begin, it is beneficial to determine the length of the longest sub-array you currently possess. Once you have this information, you can then proceed to pad all sub-arrays to ensure they are equal in length.

Below is a code snippet that includes two functions: one for calculating the maximum length and another for padding the arrays:

function findMaxLength(array) {
  let maxLength = 0;
  for (let i = 0; i < array.length; i++) {
    if (array[i].length > maxLength)
      maxLength = array[i].length;
  }
  return maxLength;
}

function addPadding(array, maxLen) {
  for (let i = 0; i < array.length; i++) {
    for (let j = array[i].length; j < maxLen; j++)
      array[i].push(0);
  }
}

const myArray = [
  [7, 9, 10],
  [6, 9],
  [5, 9]
];

addPadding(myArray, findMaxLength(myArray));

console.log(myArray);

Answer №5

Looks like a square matrix is needed from a 2D array, you can achieve this with the following code:

var myarr = [
  [1, 2],
  [3, 4, 5],
  [6, 7, 8, 9] // <--- just for illustration
];

var rows = myarr.length;
var cols = 0;

for(var i = 0; i < myarr.length; i++){
  if(myarr[i].length > cols)
    cols = myarr[i].length;
}

var limit = rows > cols ? rows : cols;
for(var i = 0; i < limit; i++){
  if(myarr[i] == undefined)
    myarr[i] = new Array(limit);
  for(var j = 0; j < limit; j++){
    if(typeof myarr[i][j] == "undefined")
      myarr[i][j] = 0;
  }
}

for(var i = 0; i < limit; i++){
  console.log(JSON.stringify(myarr[i]));
}

Answer №6

let maxLen=0;
for(let i=0;i<myarr.length;i++){
   if(myarr[i].length>maxLen){
      maxLen=myarr[i].length
  }
}
for(let i=0;i<myarr.length;i++){
    if(myarr[i].length!=maxLen){
    addZeros(myarr[i])
    }
  }
function addZeros(child){
    while(child.length!=maxLen)
     {child.push(0);}
}

Answer №7

To handle a nested array filled with numbers, you can employ a recursive approach similar to the one demonstrated below:

function replaceNumbers(array, value){

  for(var i=0; i<array.length; i++){    
    if(typeof(array[i]) === 'number'){
        array[i] = value;
    }else{
        replaceNumbers(array[i], value);
    }
  } 

}
var exampleArray = [5,[3,8,-1,[3,4,5,2,1],[2] ],[[2,2],[3]],[[2,3],[4]],[[2,4],[5]]];
replaceNumbers(exampleArray, 0);

Answer №8

How to utilize the map function

var array = [ 
           [ 7, 9, 10 ], 
           [ 6, 9], 
           [ 5, 9] 
       ]

       var newArray = array.map(function(element){
       var tempArray = [];
        if(element.length < 3)
            element.push(0);

         tempArray.push(element);
         return tempArray;

       });

      alert(newArray);

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

Implementing Vuetify select with data fetched from a Rest API

How can I populate a Vuetify select dropdown with data from a Rest API using the code provided below? Vuetify code: <div class="mb-4"> <v-select v-model="provinsi" :items="provins ...

JavaScript facing issues with relative file paths

In an effort to optimize page loading speed, I am using in-line CSS for above the fold code. This method is effective for pages within the root directory, but I encounter challenges when it comes to loading the rest of the CSS file at the end of pages loca ...

How to organize and sort integers in a Django model using arrays/lists

I am facing an issue with sorting a vector of three numbers that represent a model name, like 12-1-120, 12-1-139, 12-1-9, etc. My goal is to display instances of the model in descending order using Django, so it should show 12-1-139, 12-1-120, 12-1-9. Ho ...

The error message "Uncaught TypeError: Unable to access property 'url' of an undefined object - Google Image API" appeared

I am facing an issue with generating 5 random images. The first row, from flicker, is working fine. However, the second row from Google is only returning 4 images and showing an error in the console: Uncaught TypeError: Cannot read property 'url&apos ...

How to bypass middleware in Nest.js based on the header value

I am working on an application that utilizes nestjs and MiddlewareConsumer. Is there a way to skip a middleware based on a specific header value? I have reviewed the documentation and it appears that I can only skip middleware based on path or method, but ...

File not found: The specified file 'C:Self Project eact-shopper eact-shopperclientuildindex.html' does not exist

I followed the tutorial and startup code by Reed Barger exactly, but every time I try to run the server I encounter this error: Error: ENOENT: no such file or directory, stat 'C:\Self Project\react-shopper\react-shopper\client&bso ...

Strange behavior of sticky navigation when scrolling in Safari

I created a unique, single-page website for my parents completely from scratch. I included a sleek navigation menu right below the hero section that sticks to the top of the browser upon scrolling. The functionality is flawless in both Chrome and Firefox. ...

Utilize jQuery to target and select all elements whose class names begin with

If I have elements with classnames like this: .ses_0 .ses_1 .ses_2 .ses_3 How can I select all the elements and append them with a certain snippet? For example: var sessions = $('*[class*=ses_]'); for (var i = 0; i < sessions.le ...

Is it logical to combine Require.js and Angular.js for web development purposes?

As someone new to Angular.js, I am exploring how it differs from Backbone.js. Previously, we utilized Require.js to handle our package dependencies with Backbone. Is it advisable to follow the same approach with Angular.js? ...

Button click does not display Bootstrap loading icon

When I click on the button, the loading symbol fails to appear. Despite trying various solutions from StackOverflow, none have proven successful. Has anyone faced this issue and resolved it? Just for clarity, I am utilizing Bootstrap 4. $('#btn-one& ...

choose option without clicking submit button

I am looking to POST my values from a select box without using a submit button. I want the values to be automatically submitted when an option is selected. Although I have tried the sample code below, I am not getting the desired output: <form action= ...

The compilation of the Angular application is successful, however, errors are arising stating that the property does not exist with the 'ng build --prod' command

When compiling the Angular app, it is successful but encountered errors in 'ng build --prod' ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent&apo ...

Both if and else statements are carrying out code in JavaScript/jQuery

The second if statement is functioning correctly, but the first one always triggers the else statement and never stands alone. This jQuery function is enclosed within another function that is invoked under the "$(document).ready" command. I resorted to u ...

Having difficulties in loading the CSS file for my real-time chat application built with Express and Socket.io

Hi everyone, I've been struggling with an issue for the past couple of days where I can't seem to load my CSS for my Express app. If anyone has a solution, I would greatly appreciate the help. Below is my server.js code: const express = requir ...

Struggles with integrating a disappearing navigation bar when scrolling - JavaScript

I've been struggling with a fixed position navbar on my blog and I'm attempting to incorporate basic JS to hide the navbar while scrolling down and have it reappear when scrolling up. You can find the code snippet I'm trying to implement in ...

MongoDB facing difficulties in updating the database

Seeking help with my MongoDB setup as I am still new to it. I have a database where card data is stored and need to update counts when users like cards, resulting in a total likes number. I'm facing an issue where I keep getting a 400 error response ...

Traversing Through Multi-dimensional Arrays with Ruby

Exploring the concept of iterating through multidimensional arrays in Ruby on Codecademy has led me to a puzzling question. In their example, they demonstrate how to iterate through a multidimensional array using the following code snippet: things = [[1,2 ...

Problem with the authorization of the OAuth2 grant with Google

Utilizing Grant for OAuth2 authentication alongside google. All parameters are provided in config.json : { "server": { "protocol": "https", "host": "thooslo-com-shaunakde.c9.io" }, "google":{ "authorize_url": "https://accounts.google ...

Storing text data from Quilljs in Laravel 8 database

I am facing an issue with saving Quilljs Editor content to my database. Whenever I try to save it, nothing gets saved. Is there a method to successfully save Quilljs content to the database and also retrieve the data from the database to populate the Quill ...

Find the position of an element in an array that includes a specific string value using JavaScript or Node.js

I need help figuring out how to find the index of an array that contains or includes a specific string value. Take a look at my code below to see what I've tried so far: Here is a simple example: var myarr = ["I", "like", "turtles"]; var arraycontai ...