Home > OS >  Creating multidimensional arrays on-the-fly
Creating multidimensional arrays on-the-fly

Time:03-23

Take the following function to generate a square multiplication table:

function getMultTable(n) {
    /* generate multiplication table from 1 to n */
    let table = new Array(n);
    for (let i=1; i<=n; i  ) {
        table[i-1] = new Array(n);
        for (let j=1; j<=n; j  ) {
            table[i-1][j-1] = i*j;
        }
    }
    return table;
}

console.log(getMultTable(3));
// [ 
//   [ 1, 2, 3 ], 
//   [ 2, 4, 6 ], 
//   [ 3, 6, 9 ]
// ]

Why can't the following be done instead?

function getMultTable(n) {
    let table = new Array(n);
    for (let i=1; i<=n; i  ) {
        for (let j=1; j<=n; j  ) {
            table[i-1][j-1] = i*j;
        }
    }
    return table;
}

In other words, why can't a multi-dimensional array be created on-the-fly in javascript, or is it possible to do that some other way?

CodePudding user response:

Let's start from the basics, why you can't do the following

let arr;
arr[0] = 1

The answer is because arr is undefined. Well, when an array is initialized it is initialized with all its entries undefined. The operation table[i-1][j-1] = i*j is equivalent to

const row = table[i-1];
row[j-1] = i*j

So, when the table is created all its items are undefined, and the statement row[j-1] = i*j, is trying to set a property of row, in other words setting a property of undefined.

The reason is similar to why you can't run this

function getMultTable(n) {
    let table;
    for (let i=1; i<=n; i  ) {
        for (let j=1; j<=n; j  ) {
            table[i-1][j-1] = i*j;
        }
    }
    return table;
}

Only that in this case your problem is trying to read a property from undefined

CodePudding user response:

You can do it something like this:

let arr = new Array(n).fill().map(el => new Array(n).fill());
  • Related