The home where you level up

Save my spot

Multi-Dimensional Array

Term side of the Card.
Topic: Array
Unit title: Multi-Dimensional Array
Categories: Data structure
Explanation side of the Card

Explanation: The array structure that organizes data across two or more dimensions, like a table or cube. Useful for representing grids, matrices or higher-dimensional data.

Example

Wrongjs
const grid = new Array(3).fill(new Array(3).fill(0));
grid[0][0] = 1;
Rightjs
const grid = Array.from({ length: 3 }, () => new Array(3).fill(0));
grid[0][0] = 1;

fill() puts the same array object in every row; Array.from() with a callback builds a new row each time.

Common mistakes

  • Changing one cell and seeing the whole column change, because every row is the same array.

Key points

  • Rows are created with Array.from() and a factory, not fill([]), which shares one row object.
  • Nested loops iterate rows in the outer loop and columns in the inner loop, matching grid[row][col].
  • Bounds checks test both row and col before reading a neighbor cell.

Interview questions

How do I deep copy a 2D array?

Use grid.map((row) => [...row]) for numbers or strings, or structuredClone(grid) for nested objects.

Why does the order of nested loops matter for speed?

Reading row by row follows memory layout and is cache friendly. Column-first loops over large grids can be noticeably slower.

Can I store a 2D grid in a flat array?

Yes, use one array of size rows * cols and index it with row * cols + col. This is common with typed arrays.

The home where you level up

Daily 3-minute lessons to understand your AI's code.

No spam — just launch news.
Unsubscribe anytime. · Privacy Policy

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy