How to fill multidimensional array in javascript?

Viewed 13315

I tried to get this to work, but the outer loop stops after second iteration, and everything that's after it does not execute(just like it was the end of the script). I want to fill two dimensional array with any character(here i used 'q' as an example)

var A=[[],[]];
for(var i=0;i<12;i++){
    for(var j=0;j<81;j++){
        A[i][j]='q';
    }
}

It didn't work, so i put alert(i+' '+j); to see if it's even executing, and, as i wrote before, it stops after second iteration of outer loop, and then ignores rest of the script.

All I want is to have this array filled with same character in the given range(12 rows, 81 columns in this specific case), so if there's no hope in this method, i'll be glad to see one that works.

6 Answers

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

function createAndFillTwoDArray({
  rows,
  columns,
  defaultValue
}){
  return Array.from({ length:rows }, () => (
      Array.from({ length:columns }, ()=> defaultValue)
   ))
}

console.log(createAndFillTwoDArray({rows:3, columns:9, defaultValue: 'q'}))

This does the job in one line.

var A = Array(12).fill(null).map(()=>Array(81).fill('q'))

This is an array of references and a bad idea as harunurhan commented.

var A = Array(12).fill(Array(81).fill('q'));

var A=[[], []];

^ This line declares a two dimensional array of size 1x2. Try this instead:

var A = [];
for (var i = 0; i < 12; i++) {
    A[i] = [];
    for (var j = 0; j < 81; j++) {
        A[i][j] = 'q';
    }
}

Since fill() is the most succinct and intuitive, and it works as intended for immutable values, my preference would be an outer from() and an inner fill():

Array.from({length: 12}, _ => new Array(81).fill('q'));

The best approach to fill up 2D array would be like the following

let array2D = [], row = 3, col = 3, fillValue = 1
for (let i = 0; i < row; i++){
  let temp = []
  for (let j = 0; j < col; j++){
   temp[j] = fillValue
  }
  array2D.push(temp)
}

You need to initialise a new array for i each time the first loop runs, and you don't need to set the layout of the array before you create it (Remove the [], [] inside the declaration of A). Try this:

var A = [];
for (var i = 0; i < 12; i++) {
  A[i] = [];
  for (var j = 0; j < 81; j++) {
    A[i][j] = 'q';
  }
}
console.log(A);
.as-console-wrapper { 
    max-height: 100% !important; 
    top: 0; 
}

Related