SoFunction
Updated on 2025-04-06

How to quickly and efficiently create JavaScript 2D array method detailed explanation

introduction

In JavaScript, creating two-dimensional arrays is a common requirement, especially when developing web applications and games.

However, to avoid using complex code to create two-dimensional arrays, we need a fast and efficient approach.

Method 1: Create a 2D array using a double loop

In JavaScript, using double loops is a common way to create two-dimensional arrays. Here is a sample code:

function createArray(rows, cols) {
  var arr = new Array(rows);
  for (var i = 0; i < rows; i++) {
    arr[i] = new Array(cols);
    for (var j = 0; j < cols; j++) {
      arr[i][j] = 0;
    }
  }
  return arr;
}
// Create a 3x3 2D arrayvar myArray = createArray(3, 3);
// Print a two-dimensional array(myArray);

In the above code, we first create a line numberrows, the number of columns iscolsarray of . Then, use a double loop to iterate through the array, setting each element to 0.

Although this approach is simple, it may not be efficient when dealing with large two-dimensional arrays.

Method 2: Create a 2D array using ()

ES6's()Methods provide a more efficient way to create two-dimensional arrays. Here is a sample code:

function createArray(rows, cols) {
  return ({ length: rows }, () => new Array(cols).fill(0));
}
// Create a 3x3 2D arrayvar myArray = createArray(3, 3);
// Print a two-dimensional array(myArray);

In the above code, we use()Method to create row countrows, the number of columns iscolsarray of . Then, we used the callback functionnew Array(cols).fill(0), it will return a column number ascols, arrays with elements of 0. Finally, we usefill()Method fills each row array with 0.

This approach is more concise and efficient because it only requires one loop, not two loops. So if you need to create large 2D arrays, this approach may be more suitable.

Example

Create a 2D array of 1-100

function createArray(x, y) {
  let result = [];
  for (let i = 0; i < x; i++) {
    result[i] = [];
    for (let j = 0; j < y; j++) {
      result[i][j] = i * y + j + 1;
    }
  }
  return result;
}
("createArray(10, 10) = ", createArray(10, 10));

In this example, we use two nestedforLoop to create a two-dimensional array. We first create an empty arrayresult, and then create an empty array for each row in the outer loop. In the inner loop, we use(i * y + j + 1)to assign an incremental value to each element and store it in the corresponding row and column positions. Finally, we return the entire two-dimensional array. Although this method is usedforloop, but in some cases it may be simpler and more intuitive than others.

function createArray(x, y) {
  return ({ length: x }, (_, i) =>
    ({ length: y }, (_, j) => j + i * y + 1)
  );
}
("createArray(10, 10) = ", createArray(10, 10));

In this example, we use the () method to create a two-dimensional array. We first create an array with rows x and columns y, and then use (j + i * y + 1) in the callback function to assign an incremental value to each element. Finally, we collect the row arrays in a large array and return the entire two-dimensional array. This method is a common way to create two-dimensional arrays using the () method.

function createArray(x, y) {
    let count = 1;
    return ({ length: x }, () =>
      ({ length: y }, () => count++)
    );
  }
("createArray(10, 10) = ", createArray(10, 10));

In this example, we also use the () method to create a two-dimensional array. We create a counter variable count externally, and then use count++ in the callback function to assign an incremented value to each element. Finally, we collect the row arrays in a large array and return the entire two-dimensional array. This approach is similar to Example 1, except that the counter variable is used instead of (j + i * y + 1).

function createArray(x, y) {
    let count = 1;
    return Array(x).fill().map(() => Array(y).fill().map(() => count++));
  }
("createArray(10, 10) = ", createArray(10, 10));

In this example, we use the fill() and map() methods to create a two-dimensional array. We first use Array(x).fill() to create an array of size x, and then use Array(y).fill().map(() => count++) in the callback function to create an array of rows of size y and fill it with incremental values. Finally, we collect the row arrays in a large array and return the entire two-dimensional array. Although this method uses more method calls, it may be faster than others in some cases.

in conclusion

Whether you are creating a small or large 2D array, both methods are useful. The method of creating a two-dimensional array using a double loop is simple, but it can be inefficient when dealing with large arrays. use()Methods to create two-dimensional arrays are more concise and efficient, and are suitable for large arrays. Therefore, you can choose the method that suits you according to your needs.

Hopefully this article will help you better understand how to create JavaScript 2D arrays and how to choose the method that suits you. Whether you are developing a web application, a game, or another application, creating an efficient 2D array is an important task. Although there are several ways to achieve this task, use()Methods are usually better choices.

Remember that creating an efficient program depends not only on the technology used, but also on your design and implementation. Therefore, during the development process, you need to consider other aspects, such as the readability, maintainability and scalability of your code. Only after you have taken these factors into consideration can you truly create an excellent program.

The above is a detailed explanation of how to quickly and efficiently create JavaScript two-dimensional array methods. For more information about JavaScript two-dimensional array creation, please pay attention to my other related articles!