DEV Community

Cover image for Mastering JavaScript: Multiple Ways to Generate a Two-Dimensional Array

Mastering JavaScript: Multiple Ways to Generate a Two-Dimensional Array

yanhaijing on April 13, 2024

I often ask in interviews: Can you generate a two-dimensional array using JavaScript? This question might seem simple, but it actually reveals the ...
Collapse
 
jahid6597 profile image
MD. JAHID HOSSAIN • • Edited

Another way, we can implement method 3 using Array.fill() without map

function create2DArray(m, n) {
    return Array(m).fill(Array(n).fill(0));
}
Enter fullscreen mode Exit fullscreen mode

--UPD:

function create2DArray(m, n) {
    return Array.from({ length: m }, () => Array(n).fill(0));
}
Enter fullscreen mode Exit fullscreen mode

This version of create2DArray uses Array.from to create a new array for each row, ensuring that each row is independent of the others. Now modifying one row won't affect the others.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ •

This is incorrect. You will create an array of multiple copies of the same array:

// Create a 3x3 array
const myArray = create2DArray(3,3)

// Set 'one' item to 9
myArray[0][1] = 9

// Surprise!
console.log(myArray[0][1])  // 9
console.log(myArray[1][1])  // 9!!
console.log(myArray[2][1])  // 9!!

console.log(myArray[0] === myArray[1]) // true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yanhaijing profile image
yanhaijing •

Indeed, there is this issue. Thumbs up for you!

Collapse
 
jahid6597 profile image
MD. JAHID HOSSAIN •

Thank you for identifying that @jonrandy

function create2DArray(m, n) {
    return Array.from({ length: m }, () => Array(n).fill(0));
}

const myArray = create2DArray(3, 3);
myArray[0][1] = 9;

console.log(myArray[0][1]);  // 9
console.log(myArray[1][1]);  // 0
console.log(myArray[2][1]);  // 0

console.log(myArray[0] === myArray[1]); // false

console.log(myArray[1] === myArray[2]); // false
// myArray[1] and myArray[2] are different arrays, even if they contain the same values. So, myArray[1] === myArray[2] returns false.

console.log(myArray) // [[0, 9, 0], [0, 0, 0], [0, 0, 0]] 
Enter fullscreen mode Exit fullscreen mode

This version of create2DArray uses Array.from to create a new array for each row, ensuring that each row is independent of the others. Now modifying one row won't affect the others.

Thread Thread
 
yanhaijing profile image
yanhaijing •

This shares a striking resemblance to Method 2 in its ingenuity.

Collapse
 
yanhaijing profile image
yanhaijing •

Thank you for your feedback, this is a better approach.

Collapse
 
jean_jorgemichel_8048416 profile image
Jean Jorge Michel •

I prefer try it in a way closer to OO paradigme, creating a function that will represent a matrix in general this give to us a more reusefull project feature.

var matrix = {
    create: function(rows, columns) {
        var newMatrix = [];
        for (var i = 0; i < rows; i++) {
            var row = [];
            for (var j = 0; j < columns; j++) {
                row.push(0); // Zero for default
            }
            newMatrix.push(row);
        }
        return newMatrix;
    },
    set: function(matrix, row, column, value) {
        if (row >= 0 && row < matrix.length && column >= 0 && column < matrix[0].length) {
            matrix[row][column] = value;
        } else {
            console.error("Index out of matrix.");
        }
    },
    get: function(matrix, row, column) {
        if (row >= 0 && row < matrix.length && column >= 0 && column < matrix[0].length) {
            return matrix[row][column];
        } else {
            console.error("Index out of matrix.");
            return undefined;
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

Now we can do:

var m4x4 = matrix.create(4, 4);
matrix.set(m4x4, 0, 0, 1);
console.log(m4x4);
// [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yanhaijing profile image
yanhaijing •

good job

Collapse
 
jimzzzz profile image
Jimmy •

One more way :)

function create2DArray(m, n) {
    return [...Array(m)].map(() =>Array(n).fill(0))
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hashirdev profile image
Hashir Afzal •

Nice in depth knowledge of array and js thanks keep it up

Collapse
 
yanhaijing profile image
yanhaijing •

Thank you for your support.

Collapse
 
sharmi2020 profile image
Sharmila kannan •

Nice article

Collapse
 
yanhaijing profile image
yanhaijing •

Thank you for your support.

Collapse
 
greenteaisgreat profile image
Nathan G Bornstein •

Just to add one more way to do it (using one of the tips I learned from this article!):

[...Array(n)].map(x => []);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nangegao profile image
NangeGao •

NB. Did you complete the article word by word or translate it using tools?

Collapse
 
yanhaijing profile image
yanhaijing •

Do you have any questions?

Collapse
 
nangegao profile image
NangeGao •

Give DaLao a call !!!

Thread Thread
 
yanhaijing profile image
yanhaijing •

You are the best!