JavaScriptLoops, Arrays & Strings

Multi-Dimension Array

Learn how to use multi-dimensional arrays in JavaScript to store and manage complex grid or table-like data.

What is a Multi-Dimension Array?Link to this section

A multi-dimensional array is an array that contains other arrays as its elements. You can think of it like a spreadsheet or a grid filled with rows and columns.

This example creates a 2x3 grid of numbers and prints the item at row 0, column 1.

  • `const grid` is the variable storing our main array
  • `[1, 2, 3]` is the first inner array representing the first row
  • `grid[0]` selects the first inner array
  • `[1]` accesses the second item inside that inner array

Multi-dimensional arrays are used to represent matrices, game boards, and tables of data inside your programs.

Why Do We Need Multi-Dimension Arrays?Link to this section

Regular one-dimensional arrays only let you store a single list of items, but real-world data often comes in tables or grids.

  • Store student marks across multiple subjects and terms
  • Represent a chess board or tic-tac-toe game grid
  • Manage seating charts in a cinema or theater
  • Keep track of pixel colors in digital images
  • Record monthly sales data broken down by department and week

We use a 2D array to map out cinema seats and update a seat from free to booked.

This shows how a 2D array organizes data into rows and columns, making it easy to look up or modify specific items.

About Multi-Dimension ArraysLink to this section

Multi-dimensional arrays in JavaScript are simply arrays of arrays. You can create arrays with three or more dimensions by nesting arrays even further. To access data, you chain square brackets together for each dimension you need to cross.

DimensionsVisual AnalogyAccess Syntax
1D ArrayA single checklistarray[index]
2D ArrayA spreadsheet or gridarray[row][column]
3D ArrayA Rubik's cubearray[depth][row][column]

Accessing a 3D array requires three sets of brackets for layer, row, and column.

Types and Operations on Multi-Dimension ArraysLink to this section

1. Creating and Initializing 2D ArraysLink to this section

You can declare a 2D array manually by writing out the rows inside square brackets. This is the safest and most common way to make small grids.

Creating a tic-tac-toe board using a 3x3 array.

tip

Always format your multi-dimensional array code with one row per line to keep it readable.

2. Reading Values with Nested LoopsLink to this section

To look at every single item in a 2D array, you must use nested loops. The outer loop goes through each row, and the inner loop goes through each column inside that row.

This loops through every element in a 2x2 matrix and prints it.

warning

Using `matrix.length` in the inner loop instead of `matrix[i].length` will cause errors if your rows have different lengths.

3. Modifying Multi-Dimension Array ElementsLink to this section

You can change any value in a multi-dimensional array by specifying the exact row and column index and assigning a new value.

Updating the price at row 0, column 1 from 20 to 25.

note

Changes made to an inner array update the main multi-dimensional array immediately.

4. Adding Rows and ColumnsLink to this section

You can add new rows to a 2D array using the push method, or add items to an existing inner array by pushing to it.

Adding a brand new row to our tasks array.

tip

Make sure new rows have the same number of columns if you are treating your array like a strict grid.

5. Jagged Arrays (Uneven Rows)Link to this section

JavaScript arrays do not require all rows to be the same length. An array where rows have different lengths is called a jagged array.

Rows can have varying numbers of columns without breaking JavaScript.

note

Jagged arrays are great for storing data where rows represent different amounts of items, like list of items per user.

Common Traps with Array CopyingLink to this section

When copying multi-dimensional arrays, simple methods like slice only copy references to the inner arrays, not the inner arrays themselves. This leads to unexpected bugs where changing the copy changes the original.

Shallow copying a 2D array leaves inner arrays shared between both variables.

warning

To truly clone a multi-dimensional array without sharing inner references, you need deep cloning techniques or structured cloning.

Complete Coding ExampleLink to this section

Calculates and prints the test score average for each student stored in a 2D array.

This program loops through a 2D array containing student names and grades, calculating the average for each person.

Important NotesLink to this section

  • A multi-dimensional array is an array containing other arrays.
  • Use two sets of square brackets to access elements in a 2D array [row][column].
  • The outer loop typically handles rows, while the inner loop handles columns.
  • JavaScript allows jagged arrays where inner rows have different lengths.
  • Always use `matrix[i].length` in your inner loops to avoid out-of-bounds errors.
  • Shallow copies like spread operators do not duplicate inner arrays.
  • You can add new rows using the push method.
  • Make sure index numbers start at 0 for both rows and columns.
  • Multi-dimensional arrays are essential for building grids and games.
  • Keeping code formatted with one row per line helps prevent confusion.

SummaryLink to this section

In this lesson, you learned how to store and manage complex data using multi-dimensional arrays. By nesting arrays inside arrays and using nested loops, you can build powerful structures like grids, scoreboards, and tables. These skills prepare you for advanced data processing and game development in future lessons.

Check Your UnderstandingLink to this section

Javascript Multi-Dimension Array quiz
Question 1 of 6

How do you access the value 7 in `const arr = [[1, 2], [5, 7]];`?

Practice ChallengesLink to this section

1. Print Matrix Row

easy

Create a 2D array representing a 2x2 grid of numbers. Write a loop to print all numbers in the first row.

Expected output

1
2

Hint: Access the first row using index 0 and loop through its elements.

2. Tic-Tac-Toe Winner Checker

easy

Create a 3x3 2D array representing a tic-tac-toe board filled with 'X' and 'O'. Check and print whether the top-left cell matches the middle cell.

Expected output

Match: false

Hint: Compare board[0][0] with board[1][1].

3. Grid Sum Calculator

medium

Create a 2D array of numbers with 2 rows and 2 columns. Use nested loops to calculate and print the total sum of all numbers.

Expected output

10

Hint: Keep a running total variable outside both loops and add each grid item to it.

4. Find Maximum Value

medium

Create a 2D array with different numbers. Write code using nested loops to find and print the highest number in the entire grid.

Expected output

95

Hint: Assume the first element is the max, then compare every other element against it.

5. Dynamic Grid Generator

hard

Write code that creates a 3x3 grid where each cell contains the product of its row index multiplied by its column index. Print the grid row by row.

Expected output

0 0 0
0 1 2
0 2 4

Hint: Use nested loops with i * j and push the results into inner arrays.

Rate this content

Sign in to rate

Discussion

Sign in to join the discussion