Multidimensional Arrays
Multidimensional arrays are arrays of arrays — used for grids, matrices, tables, game boards, and pixel data. Access elements with multiple indices: grid[row][col].
2D Arrays
- 2D array — Array of arrays: [[1,2,3], [4,5,6], [7,8,9]]. Like rows and columns
- Access — matrix[row][col]. matrix[0][1] = first row, second column
- Iterate — Nested loops: outer for rows, inner for columns
- Use cases — Game boards (tic-tac-toe, chess), spreadsheets, pixel grids, seating charts
- flat() — Convert 2D to 1D: [[1,2],[3,4]].flat() = [1,2,3,4]
2D Array Code
// 2D array (matrix)
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Access elements
console.log(matrix[0][0]); // 1 (top-left)
console.log(matrix[1][1]); // 5 (center)
console.log(matrix[2][2]); // 9 (bottom-right)
// Iterate with nested loops
for (let row = 0; row < matrix.length; row++) {
let line = "";
for (let col = 0; col < matrix[row].length; col++) {
line += matrix[row][col] + " ";
}
console.log(line);
}
// Real-world: Tic-tac-toe board
const board = [
["X", "O", "X"],
["O", "X", " "],
[" ", "O", "X"]
];
board.forEach(row => console.log(row.join(" | ")));
// Create 3x3 grid filled with 0
const grid = Array.from({ length: 3 }, () => Array(3).fill(0));
console.log(grid); // [[0,0,0], [0,0,0], [0,0,0]]Tip
Tip
Use Array.from({ length: rows }, () => Array(cols).fill(0)) to create 2D arrays. The arrow function creates a NEW inner array for each row, preventing the shared reference bug.
map/filter return new arrays; sort/splice mutate the original
Common Mistake
Warning
Creating 2D arrays with Array(3).fill(Array(3).fill(0)) makes all rows share the SAME inner array. Changing grid[0][1] also changes grid[1][1] and grid[2][1]. Always use Array.from with a factory function.
Practice Task
Note
Build a 2D grid: (1) Create a 3x3 tic-tac-toe board initialized with empty strings. (2) Place X at position [0][0] and O at [1][1]. (3) Display the board using forEach and join('|'). (4) Check if any row has three of the same symbol.
Quick Quiz
Key Takeaways
- Multidimensional arrays are arrays of arrays — used for grids, matrices, tables, game boards, and pixel data.
- 2D array — Array of arrays: [[1,2,3], [4,5,6], [7,8,9]]. Like rows and columns
- Access — matrix[row][col]. matrix[0][1] = first row, second column
- Iterate — Nested loops: outer for rows, inner for columns