Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Creating multidimensional arrays on-the-fly

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

You can do it something like this:

let arr = new Array(n).fill().map(el => new Array(n).fill());
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!