yanhaijing

Posted on

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

I often ask in interviews: Can you generate a two-dimensional array using JavaScript? This question might seem simple, but it actually reveals the interviewee's proficiency with JavaScript. Just as there are various methods to achieve the same goal, there are also various methods to generate a two-dimensional array. Today, let's explore the answers behind this question and uncover the secrets of generating two-dimensional arrays.

Knowing different methods not only allows us to handle different scenarios more adeptly but also showcases our deep understanding of JavaScript during interviews. After all, in the world of programming, being adaptable is often more important than rote memorization.

I recommend that while reading this article, try to think about how you would implement each method yourself before looking at the solution. This approach will yield more insights.

## Creating a One-Dimensional Array

Before we tackle two-dimensional arrays, let's learn how to create a one-dimensional array. There are several ways to do this; here are some common methods:

### 1.Array Literals

This is the simplest way to create an array, just using square brackets [].

``````let arr = [1, 2, 3];
``````

### 2.Using the Array Constructor

The above array can also be created using the Array constructor.

``````let arr = new Array(1, 2, 3);
``````

However, when using the Array constructor, it's important to note that if only one parameter is passed, it denotes the length of the array. To create an array with a single element, in addition to the above method, you can also use the Array.of() method. When multiple parameters are present, Array.of and the Array constructor have the same effect.

``````let arr = Array.of(2);
console.log(arr); // [2]
``````

You can use this Array constructor to create an array of a specified length. But it's important to note that the elements of the array created this way are empty slots, not undefined.

``````let arr = new Array(3);
console.log(arr); // [empty × 3]
``````

To avoid the issue of empty slots, you can combine this with the Array.fill() method to populate the array:

``````let arr = new Array(3).fill(0);
console.log(arr); // [0, 0, 0]
``````

### 3.Using Array.from()

The Array.from() method can create a new array instance from an array-like or iterable object. It can also take a map function as a second argument to initialize array elements.

``````let arr = Array.from({ length: 3 }, () => 0);
console.log(arr); // [0, 0, 0]
``````

### 4.Using Spread Operator and Array()

You can combine the spread operator (...) with the Array() constructor to create and initialize an array.

``````let arr = [...Array(3)].map(() => 0);
console.log(arr); // [0, 0, 0]
``````

Mastering these methods for creating one-dimensional arrays can help us more flexibly handle various programming scenarios. In the following sections, we'll explore how to extend these methods to create two-dimensional arrays.

## Introduction to Two-Dimensional Arrays

A two-dimensional array, as the name suggests, is an array of arrays. In JavaScript, it can be used to represent matrices, grids, or any data structure that requires rows and columns. Imagine a chessboard, where each row is an array, and the entire chessboard is a two-dimensional array.

Two-dimensional arrays often appear in programming interviews, especially when dealing with matrix-related problems. For example:

1. Matrix Related: Given an n x n two-dimensional matrix, rotate it by 90 degrees in place.
2. Island Count: Given a two-dimensional grid composed of '1's (land) and '0's (water), calculate the number of islands.
3. Dynamic Programming: Solve the maximum subarray sum problem.

Mastering operations on two-dimensional arrays is crucial for solving these problems, so understanding how to effectively generate and manipulate two-dimensional arrays in JavaScript is very useful.

There are many methods to generate two-dimensional arrays, and today we'll explore the following, analyzing their pros and cons:

1. Using Nested Loops
2. Using Array.from()
3. Using Array.fill() and map()
4. Using Spread Operator and map()

### 1.Using Nested Loops

This is the most straightforward method. First, create an outer array, then create an inner array at each position.

``````function create2DArray(m, n) {
let arr = new Array(m);
for (let i = 0; i < m; i++) {
arr[i] = new Array(n);
for (let j = 0; j < n; j++) {
arr[i][j] = 0; // or other initial values
}
}
return arr;
}
``````

Advantages: Intuitive and easy to understand.

### 2.Using Array.from()

Array.from() can create a new array based on given parameters, and map() can process each element of the array.

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

Disadvantages: May take some time for beginners to understand this syntax.

### 3.Using Array.fill() and map()

Similar to the previous method, but uses Array.fill() to create the initial array.

``````function create2DArray(m, n) {
return Array(m)
.fill()
.map(() => Array(n).fill(0));
}
``````

Disadvantages: Similar to the previous method, it may be somewhat challenging for beginners.

### 4.Using Spread Operator and map()

The spread operator (...) can be used to expand an array, combined with map() to create a two-dimensional array.

``````function create2DArray(m, n) {
return [...Array(m)].map(() => Array(n).fill(0));
}
``````

Advantages: Code is concise and easy to understand.
Disadvantages: Performance might be slightly inferior to other methods.

## Conclusion

Each method has its advantages and disadvantages, and which one you choose depends on your specific needs and personal preferences. If you value code simplicity, then using Array.from() might be a good choice. If you prefer code that is easy to understand and maintain, then using nested loops might be more suitable for you.

Mastering the various methods to generate two-dimensional arrays is an essential skill for every JavaScript developer. Through these methods, we can flexibly handle various data structures and algorithm challenges. I hope this article helps you better understand and use these techniques. Next time this question comes up in an interview, you'll be able to confidently provide an answer.

## My Recommended Method

Among all the methods, I personally prefer using the Array.from() method because it's very powerful. Of course, the Array.fill method is also excellent, with the advantage of being semantic and more readable.

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

Thank you for reading this article! Mastering the multiple ways to generate two-dimensional arrays in JavaScript can help us handle different programming challenges more effortlessly. Each method has its unique features, which one do you like best? Feel free to share your thoughts and experiences in the comments section, and let's improve together!

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));
}
``````

--UPD:

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

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.

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
``````

yanhaijing

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

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]]
``````

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.

yanhaijing

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

yanhaijing

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

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;
}
}
};
``````

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]]
``````

yanhaijing

good job

Hashir Afzal

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

yanhaijing

Jimmy

One more way :)

``````function create2DArray(m, n) {
return [...Array(m)].map(() =>Array(n).fill(0))
}
``````

Sharmila kannan

Nice article

yanhaijing

NangeGao

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

yanhaijing

Do you have any questions?

NangeGao

Give DaLao a call !!!