# Multi-Dimensional Array

> The Multi-Dimensional Array is a data structure that stores elements in multiple dimensions, such as 2D grids or 3D matrices.

## How do I create a 2D array in JavaScript?

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.

- Topic: Array
- Type: data structure

## Example

Wrong:

```js
const grid = new Array(3).fill(new Array(3).fill(0));
grid[0][0] = 1;
```

Right:

```js
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.

## Related cards

- [One-Dimensional Array](https://wonderium.dev/algorithms/one-dimensional-array.md)
- [Matrix](https://wonderium.dev/algorithms/matrix.md)
- [Array.from()](https://wonderium.dev/js/array-from.md)
- [.fill()](https://wonderium.dev/js/array-fill.md)
- [structuredClone()](https://wonderium.dev/js/structured-clone.md)

---

- Level: [Algorithms](https://wonderium.dev/algorithms.md)
- HTML version: https://wonderium.dev/algorithms/multi-dimensional-array
- Last updated: 2026-11-25
