Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Multidimensional Arrays

Multidimensional arrays are arrays of arrays and are common in grid or table data.

They require two indexes to access individual elements.

Why We Need It

Many problems involve grids, boards, or matrices. Multidimensional arrays model them directly.

Understanding access and iteration patterns makes these problems easier.

Syntax

const grid = [[1, 2], [3, 4]]
grid[row][col]

Basic Example

1. Create a grid

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

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

Access row 0, column 1.

Real World Example

2. Nested loops

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

for (let r = 0; r < grid.length; r++) {
  for (let c = 0; c < grid[r].length; c++) {
    console.log(grid[r][c]);
  }
}

Use nested loops for traversal.

Multiple Use Cases

Arrays of Arrays

A multidimensional array is an array that contains other arrays.

This is common for grids, tables, and matrices.

Access by Index

Use two indexes to access row and column positions.

grid[row][col] is the typical pattern.

Looping

Use nested loops to iterate through rows and columns.

Keep the inner loop simple for performance.

More Examples

3. Update a cell

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

grid[1][0] = 99;
console.log(grid);

Update a specific cell by index.

4. Flatten

const grid = [[1, 2], [3, 4]];
const flat = grid.flat();

console.log(flat);

flat reduces one level of nesting.

Comparison

Without

const row0col1 = grid[0][1];

With

const row0col1 = grid[0][1]; // direct access

Common Mistakes and Fixes

Assuming rectangular shape

Rows can have different lengths; check before indexing.

Mixing row and column

Be consistent with grid[row][col].

Complex nested loops

Extract helper functions for clarity.

Interview Questions

How do you loop a grid?

Use nested loops for rows and columns.

Can you flatten a grid?

Yes, use flat() or reduce with concat.

Are rows always equal length?

No, arrays can be jagged.

Practice Problem

Practice: Print all values of a 2x2 grid using nested loops.

const grid = [[1, 2], [3, 4]];
// TODO: print all values

One Possible Solution

const grid = [[1, 2], [3, 4]];
for (let r = 0; r < grid.length; r++) {
  for (let c = 0; c < grid[r].length; c++) {
    console.log(grid[r][c]);
  }
}

Frequently Asked Questions

What is a multidimensional array?

An array that contains other arrays.

How do you access a value?

Use two indexes: grid[row][col].

Can rows be different lengths?

Yes, JavaScript arrays are not required to be rectangular.

Try It Yourself

Try changing values and indexes in the grid.