How can I create a two dimensional array in JavaScript?

To create a two-dimensional (2D) array in JavaScript, you need to construct an array where each element is itself an array. Below are detailed methods with examples to achieve this safely and efficiently, avoiding common pitfalls like shared references.

1. Basic 2D Array Initialization

Manually define each row as a separate array.

// Example: 3x3 matrix
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(matrix);
// Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

2. Fixed-Size 2D Array (Avoid Shared References)

Use loops to create distinct rows.

const rows = 3;
const cols = 3;
const matrix = [];

for (let i = 0; i < rows; i++) {
  matrix[i] = new Array(cols).fill(0); // Each row is a new array
}

console.log(matrix);
// Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Why Not Use fill(new Array(cols))?
This creates shared references to the same inner array (modifying one row affects all rows):

// ❌ Incorrect: Shared references
const badMatrix = new Array(3).fill(new Array(3).fill(0));
badMatrix[0][0] = 1; // Changes all rows
console.log(badMatrix);
// Output: [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

3. Using Array.from()

Create a 2D array with a specified size and default value.

const rows = 2;
const cols = 4;

const matrix = Array.from({ length: rows }, () => 
  Array.from({ length: cols }, () => 0)
);

console.log(matrix);
// Output: [[0, 0, 0, 0], [0, 0, 0, 0]]

4. Using map() with fill()

Avoid sparse arrays by using fill(null) before map().

const rows = 3;
const cols = 3;

const matrix = new Array(rows)
  .fill(null) // Avoid sparse array issues
  .map(() => new Array(cols).fill(0));

console.log(matrix);
// Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

5. Jagged Arrays (Rows of Different Lengths)

Define rows with varying column lengths.

const jaggedArray = [
  [1, 2, 3],
  [4, 5],
  [6, 7, 8, 9]
];

console.log(jaggedArray);
// Output: [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

6. Dynamic Initialization with Values

Use nested loops to fill the array dynamically.

const rows = 3;
const cols = 3;
const matrix = [];

for (let i = 0; i < rows; i++) {
  matrix[i] = [];
  for (let j = 0; j < cols; j++) {
    matrix[i][j] = i * j; // Example: i * j
  }
}

console.log(matrix);
// Output: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

7. Functional Approach with Array.fill() and map()

Initialize with a default value using functional programming.

const rows = 2;
const cols = 2;

const matrix = new Array(rows)
  .fill()
  .map(() => new Array(cols).fill("default"));

console.log(matrix);
// Output: [['default', 'default'], ['default', 'default']]

Key Takeaways

MethodUse CaseAvoids Shared References?
Manual InitializationSmall, fixed-size arraysYes
LoopsCustom sizes and dynamic initializationYes
Array.from()Clean syntax for fixed-size arraysYes
map() + fill()Functional programming styleYes
Jagged ArraysRows with varying lengthsYes

Common Mistakes

  1. Shared References: Using fill(new Array(cols)) causes all rows to reference the same array.
  2. Sparse Arrays: new Array(rows).map(...) skips empty slots; use fill(null) first.
  3. Dynamic Sizes: For variable row lengths, explicitly define each row’s columns.

By following these methods, you can create 2D arrays in JavaScript safely and efficiently!

Leave a Reply

Your email address will not be published. Required fields are marked *