Online Compiler logoOnline Compiler
Array Concepts

JavaScript Multidimensional Arrays

Create and work with nested arrays (arrays containing arrays) for complex data structures.

What are Multidimensional Arrays?

A multidimensional array is an array that contains other arrays. The most common type is a 2D array (array of arrays), which represents a matrix or table structure.

Create 2D and 3D Arrays in JavaScript

// 2D Array (matrix)
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// 3D Array
const cube = [
  [[1, 2], [3, 4]],
  [[5, 6], [7, 8]]
];

This example shows how to create multidimensional arrays such as 2D matrices and 3D nested arrays for storing structured data.

Creating Multidimensional Arrays

Create a 2D Array

Create a Dynamic 2D Array with Default Values

// Literal syntax
const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// Dynamically create a 2D array
const rows = 3;
const cols = 4;
const newGrid = Array(rows).fill(null).map(() => Array(cols).fill(0));
console.log(newGrid);
// [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

This example demonstrates how to create a grid or matrix dynamically using Array().fill() and map() to generate rows and columns.

Create with Different Data Types

Multidimensional Array with Different Data Types

const mixed = [
  [1, 'a'],
  [true, { name: 'John' }],
  [[1, 2], [3, 4]]
];

Nested arrays can store mixed data types like numbers, strings, objects, and even other arrays within the same structure.

Accessing Elements

Access 2D Array Elements

Access Elements in a 2D Array Using Indexes

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

console.log(matrix[0][0]); // 1 (row 0, col 0)
console.log(matrix[1][2]); // 6 (row 1, col 2)
console.log(matrix[2][0]); // 7 (row 2, col 0)

Use two indexes [row][column] to access values inside a 2D array matrix.

Access 3D Array Elements

Access Values in a 3D Nested Array

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

console.log(cube[0][0][0]); // 1
console.log(cube[1][1][1]); // 8

In a 3D array, you use three indexes to access elements inside deeply nested arrays.

Iterating Through Multidimensional Arrays

Nested forEach Loops

Loop Through a 2D Array with Nested forEach

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

matrix.forEach((row, rowIndex) => {
  row.forEach((element, colIndex) => {
    console.log(`[${rowIndex}][${colIndex}] = ${element}`);
  });
});

This example uses nested forEach() loops to iterate through rows and columns of a multidimensional array.

Nested for Loops

Traverse a Multidimensional Array Using for Loops

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

for (let i = 0; i < matrix.length; i++) {
  for (let j = 0; j < matrix[i].length; j++) {
    console.log(matrix[i][j]);
  }
}

Traditional for loops allow precise control when iterating through rows and columns in nested arrays.

Using map() on 2D Array

Use map() to Transform Values in a 2D Array

const matrix = [
  [1, 2, 3],
  [4, 5, 6]
];

const doubled = matrix.map(row => 
  row.map(element => element * 2)
);

console.log(doubled);
// [[2, 4, 6], [8, 10, 12]]

You can use nested map() methods to transform each element inside a multidimensional array.

Real-World Examples

Transpose a Matrix

Transpose a Matrix in JavaScript

const matrix = [
  [1, 2, 3],
  [4, 5, 6]
];

const transposed = matrix[0].map((_, colIndex) =>
  matrix.map(row => row[colIndex])
);

console.log(transposed);
// [[1, 4], [2, 5], [3, 6]]

This example swaps rows and columns of a matrix using map() to create a transposed array.

Tic-Tac-Toe Game Board

Represent a Game Board Using a 2D Array

const board = [
  ['X', 'O', ''],
  ['', 'X', 'O'],
  ['O', '', 'X']
];

// Check a cell
const cell = board[0][1]; // 'O'

// Update a cell
board[1][1] = 'X';

A 2D array is useful for representing grids like a Tic-Tac-Toe board where each cell holds a value.

2D Coordinates

Store and Iterate Coordinates Using Arrays

const points = [
  [10, 20],
  [30, 40],
  [50, 60]
];

points.forEach(([x, y]) => {
  console.log(`Point: (${x}, ${y})`);
});
// Point: (10, 20)
// Point: (30, 40)
// Point: (50, 60)

This example stores (x, y) coordinates in a 2D array and iterates through them using array destructuring.

Common Mistakes

❌ Sharing Reference Instead of Copying

Avoid Shared References When Creating 2D Arrays

// Wrong - all rows point to the same array
const grid = Array(3).fill(Array(3).fill(0));
grid[0][0] = 1;
console.log(grid[1][0]); // 1 (unexpected!)

// Correct
const grid = Array(3).fill(null).map(() => Array(3).fill(0));
grid[0][0] = 1;
console.log(grid[1][0]); // 0

Using fill() incorrectly can create shared references. Use map() to generate independent rows.

❌ Wrong Index Order

Correct Index Order in Multidimensional Arrays

const matrix = [
  [1, 2, 3],
  [4, 5, 6]
];

// Wrong - thinking [column][row]
console.log(matrix[3][0]); // undefined

// Correct - [row][column]
console.log(matrix[0][2]); // 3

Always access elements using [row][column]. Reversing the order can lead to unexpected results.

FAQs

How do I flatten a multidimensional array?

Flatten Nested Arrays with flat()

const matrix = [[1, 2], [3, 4], [5, 6]];
const flat = matrix.flat(); // [1, 2, 3, 4, 5, 6]
const flat2 = matrix.flat(Infinity);

The flat() method converts nested arrays into a single array. Use flat(Infinity) to flatten deeply nested arrays.

How do I copy a 2D array?

Shallow vs Deep Copy of 2D Arrays

const original = [[1, 2], [3, 4]];

// Shallow copy (copies outer array, inner arrays still referenced)
const shallow = [...original];

// Deep copy (copies everything)
const deep = JSON.parse(JSON.stringify(original));
// or
const deep = original.map(row => [...row]);

A shallow copy duplicates the outer array, while a deep copy creates a completely independent nested array structure.