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.
// Array state
// Pseudocode
Address formula
1// 2D array stored as flat 1D in memory (row-major):2address(row, col) = base + (row * numCols + col) * elementSize34// Example: 3x4 matrix, element size = 4 bytes5address(1, 2) = base + (1 * 4 + 2) * 46 = base + 6 * 47 = base + 24
Complexity
Constant time
Linear time
Quadratic time
Quadratic time
Quadratic time
Matrix multiplication
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
🎯 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
Float64Arrayindexed byr * cols + cis 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.