Arrays

Multidimensional
Arrays

2D matrices, 3D tensors, game boards, image pixels — all stored as a single flat array in memory. Understanding row-major layout unlocks the key to cache-efficient algorithms.

How do 2D arrays work in JavaScript?

A 2D array is an array of arrays: grid[row][col]. It represents tables, game boards, images and matrices. Create one with Array.from({ length: rows }, () => Array(cols).fill(0)). Don't use Array(rows).fill([]), which makes every row the same shared array. Visiting every cell takes O(rows × cols).

const rows = 3, cols = 4;
const grid = Array.from({ length: rows }, () => Array(cols).fill(0));
grid[1][2] = 5;                       // row 1, column 2

for (let r = 0; r < rows; r++)
  for (let c = 0; c < cols; c++) grid[r][c] += r + c;

const transpose = (m) => m[0].map((_, c) => m.map((row) => row[c]));

Row-major storage in memory

A 2D array like matrix[3][4] is physically one contiguous block. Row 0 occupies the first 4 slots, row 1 the next 4, and so on. The CPU address formula is one multiplication and one addition.

2D row-major layoutstep 1/3

// Array state

1
r0
2
[1]
3
[2]
4
[3]
5
[4]
6
[5]
→ Flat memory: [0,0]=1 [0,1]=2 [0,2]=3 — row 0 is contiguous

// Pseudocode

1// matrix[row][col] in flat memory
2offset = row * numCols + col
3address = base + offset * elementSize

Address formula

index-formula.pseudo
1// 2D array stored as flat 1D in memory (row-major):
2address(row, col) = base + (row * numCols + col) * elementSize
3 
4// Example: 3x4 matrix, element size = 4 bytes
5address(1, 2) = base + (1 * 4 + 2) * 4
6 = base + 6 * 4
7 = base + 24

Complexity

Element access matrix[i][j]O(1)

Constant time

Traverse one row or columnO(n)

Linear time

Traverse entire n×n matrixO(n²)

Quadratic time

Matrix addition / scalar multiplyO(n²)

Quadratic time

Matrix multiplication — naïve O(n³)O(n²)

Quadratic time

Matrix multiplication

matmul.pseudo
1function matmul(A, B):
2 C = zeros(rows_A, cols_B)
3 for i in range(rows_A):
4 for j in range(cols_B):
5 for k in range(cols_A):
6 C[i][j] += A[i][k] * B[k][j]
7 return C // O(n³) for n×n matrices
🔍Cache locality
Iterating row-by-row is up to 10× faster than column-by-column on large matrices because consecutive memory addresses stay hot in the L1 cache. Always prefer the access pattern that moves along the innermost (rightmost) index.
🧠3D arrays
A 3D array [depth][rows][cols] extends the formula: offset = depth_idx*(rows*cols) + row*cols + col. Same principle — one multiply-and-add per dimension.

🎯 Quick Check

In a row-major 5×6 matrix, what is the flat index of element [2][4]?

Multidimensional Arrays: summary

Key points

  • Index as [row][column]; keep the order consistent.
  • Grid problems often explore neighbours with direction arrays: [[0,1],[1,0],[0,-1],[-1,0]].
  • For large numeric grids, a flat Float64Array indexed by r * cols + c is faster.

Frequently asked questions

›Why did changing one row change all rows?

You created the rows with fill([]) or fill(Array(n)), which puts the same array object in every slot. Use Array.from with a function so each row is a new array.