Skip to main content

JavaScript Multidimensional Arrays

Introduction

In JavaScript, a multidimensional array is essentially an array of arrays. While JavaScript doesn't support true multidimensional arrays like some other languages do, we can create similar structures by nesting arrays within arrays. These nested structures allow us to represent complex data in tabular forms, grids, matrices, or other multi-level structures.

Multidimensional arrays are extremely useful when working with data that naturally fits into rows and columns or any scenario requiring multiple levels of organization. Common examples include game boards (like chess or tic-tac-toe), spreadsheet-like data, or pixel manipulation in graphics.

Creating Multidimensional Arrays

Two-Dimensional Arrays

A two-dimensional array is the most common type of multidimensional array, representing a table with rows and columns. Here's how to create one:

javascript
// Method 1: Creating a 2D array using array literals
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

console.log(matrix);
// Output:
// [
// [1, 2, 3],
// [4, 5, 6],
// [7, 8, 9]
// ]

We can also initialize a 2D array dynamically:

javascript
// Method 2: Creating a 2D array dynamically
const rows = 3;
const cols = 4;
const grid = [];

// Create rows
for (let i = 0; i < rows; i++) {
grid[i] = []; // Initialize each row as an empty array

// Create columns for each row
for (let j = 0; j < cols; j++) {
grid[i][j] = i * cols + j + 1; // Fill with some values
}
}

console.log(grid);
// Output:
// [
// [1, 2, 3, 4],
// [5, 6, 7, 8],
// [9, 10, 11, 12]
// ]

Three-Dimensional Arrays and Beyond

We can extend this concept to create arrays with even more dimensions:

javascript
// Creating a 3D array (like a cube)
const cube = [
[
[1, 2],
[3, 4]
],
[
[5, 6],
[7, 8]
]
];

console.log(cube);
// Output:
// [
// [[1, 2], [3, 4]],
// [[5, 6], [7, 8]]
// ]

Accessing Elements in Multidimensional Arrays

To access elements in a multidimensional array, we use multiple square bracket notation, one for each dimension:

javascript
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

// Accessing elements in a 2D array
const element = matrix[1][2]; // Accesses the element in row 1, column 2
console.log(element); // Output: 6

// Accessing elements in a 3D array
const cube = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
const cubeElement = cube[1][0][1]; // Accesses the element in the 2nd plane, 1st row, 2nd column
console.log(cubeElement); // Output: 6

Remember that array indices start at 0 in JavaScript, so matrix[1][2] refers to the element in the second row, third column.

Modifying Elements

Modifying elements works the same way as accessing them:

javascript
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

// Changing a value
matrix[0][1] = 20;

console.log(matrix);
// Output:
// [
// [1, 20, 3],
// [4, 5, 6],
// [7, 8, 9]
// ]

Iterating Through Multidimensional Arrays

Using Nested For Loops

The most common way to iterate through a multidimensional array is by using nested loops:

javascript
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

// Iterate through a 2D array
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(`Element at position [${i}][${j}]: ${matrix[i][j]}`);
}
}

// Output:
// Element at position [0][0]: 1
// Element at position [0][1]: 2
// Element at position [0][2]: 3
// Element at position [1][0]: 4
// Element at position [1][1]: 5
// ...and so on

Using forEach Method

We can also use the forEach method for cleaner code:

javascript
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

matrix.forEach((row, i) => {
row.forEach((value, j) => {
console.log(`Element at position [${i}][${j}]: ${value}`);
});
});

Using for...of Loop

The for...of loop provides an even cleaner syntax:

javascript
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

// Using for...of loops
for (const row of matrix) {
for (const element of row) {
console.log(element);
}
}

Common Operations on Multidimensional Arrays

Finding the Sum of All Elements

javascript
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

let sum = 0;
for (const row of matrix) {
for (const element of row) {
sum += element;
}
}

console.log(`Sum of all elements: ${sum}`); // Output: Sum of all elements: 45

Finding the Maximum Element

javascript
const matrix = [
[1, 20, 3],
[4, 5, 60],
[7, 8, 9]
];

let max = matrix[0][0]; // Start with the first element

for (const row of matrix) {
for (const element of row) {
if (element > max) {
max = element;
}
}
}

console.log(`Maximum element: ${max}`); // Output: Maximum element: 60

Real-World Applications

Example 1: Tic-Tac-Toe Game Board

A simple Tic-Tac-Toe game could represent its board as a 2D array:

javascript
// Initialize an empty 3x3 Tic-Tac-Toe board
const board = [
['', '', ''],
['', '', ''],
['', '', '']
];

// Make moves
board[0][0] = 'X'; // Top-left
board[1][1] = 'O'; // Center
board[2][0] = 'X'; // Bottom-left

// Display the board
function displayBoard(board) {
for (const row of board) {
console.log(row.join(' | '));
console.log('---------');
}
}

displayBoard(board);
// Output:
// X | |
// ---------
// | O |
// ---------
// X | |
// ---------

Example 2: Grade Tracking System

A teacher might use a 2D array to track student grades across different subjects:

javascript
const grades = [
// Math, Science, English, History
[95, 88, 92, 78], // Student 1
[82, 91, 84, 89], // Student 2
[91, 85, 75, 93] // Student 3
];

const studentNames = ['Alice', 'Bob', 'Charlie'];
const subjects = ['Math', 'Science', 'English', 'History'];

// Calculate average grade for each student
for (let i = 0; i < grades.length; i++) {
let sum = 0;

for (let j = 0; j < grades[i].length; j++) {
sum += grades[i][j];
}

const average = sum / grades[i].length;
console.log(`${studentNames[i]}'s average grade: ${average.toFixed(1)}`);
}

// Calculate average grade for each subject
for (let j = 0; j < subjects.length; j++) {
let sum = 0;

for (let i = 0; i < grades.length; i++) {
sum += grades[i][j];
}

const average = sum / grades.length;
console.log(`Class average for ${subjects[j]}: ${average.toFixed(1)}`);
}

// Output:
// Alice's average grade: 88.3
// Bob's average grade: 86.5
// Charlie's average grade: 86.0
// Class average for Math: 89.3
// Class average for Science: 88.0
// Class average for English: 83.7
// Class average for History: 86.7

Example 3: Image Processing

When working with images in JavaScript, you might represent pixel data as a multidimensional array:

javascript
// Simplified example of image data as a 2D array (grayscale values from 0-255)
const imageData = [
[120, 132, 145, 130],
[200, 180, 190, 210],
[150, 120, 100, 95]
];

// Increase brightness by 50 for each pixel
function increaseBrightness(image, amount) {
const newImage = [];

for (let i = 0; i < image.length; i++) {
newImage[i] = [];

for (let j = 0; j < image[i].length; j++) {
// Increase brightness but cap at 255 (maximum brightness)
newImage[i][j] = Math.min(image[i][j] + amount, 255);
}
}

return newImage;
}

const brighterImage = increaseBrightness(imageData, 50);
console.log(brighterImage);
// Output:
// [
// [170, 182, 195, 180],
// [250, 230, 240, 255],
// [200, 170, 150, 145]
// ]

Common Pitfalls and Solutions

Creating Columns with the Wrong Reference

A common mistake when initializing 2D arrays is creating rows that reference the same array:

javascript
// INCORRECT WAY - all rows point to the same array reference
const grid = new Array(3);
for (let i = 0; i < 3; i++) {
grid[i] = new Array(3).fill(0); // This is fine
}

// But this is problematic:
const badGrid = Array(3).fill(Array(3).fill(0));

// If we modify one element:
badGrid[0][0] = 1;
console.log(badGrid);
// Output: [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
// All first elements changed because each row is the same array reference!

The proper way:

javascript
// CORRECT WAY
const goodGrid = Array(3).fill().map(() => Array(3).fill(0));

// Now modifications work as expected
goodGrid[0][0] = 1;
console.log(goodGrid);
// Output: [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

Checking If a Value Exists in a Multidimensional Array

To check if a value exists in a multidimensional array:

javascript
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

function valueExists(matrix, value) {
for (const row of matrix) {
if (row.includes(value)) {
return true;
}
}
return false;
}

console.log(valueExists(matrix, 5)); // Output: true
console.log(valueExists(matrix, 10)); // Output: false

Summary

Multidimensional arrays in JavaScript are arrays of arrays, useful for representing tabular or multi-level data structures. We've covered:

  • How to create multidimensional arrays using literal notation or dynamic initialization
  • Accessing and modifying elements using bracket notation
  • Iterating through arrays using various loop techniques
  • Common operations like finding sums and maximum values
  • Real-world applications including game boards, grade tracking, and image processing
  • Common pitfalls and their solutions

Mastering multidimensional arrays opens the door to efficiently managing complex data structures in your JavaScript applications.

Additional Resources and Exercises

Resources

  1. MDN Web Docs: Arrays
  2. JavaScript.info: Arrays

Exercises

  1. Matrix Transpose: Write a function that transposes a matrix (swaps rows with columns).

  2. Multiplication Table: Create a function that generates a multiplication table as a 2D array (e.g., 10x10).

  3. Sudoku Validator: Write a function that checks if a 9x9 Sudoku grid is valid according to the rules.

  4. Matrix Operations: Implement basic matrix operations like addition and multiplication.

  5. Spiral Traversal: Write a function that returns all elements of a square matrix in spiral order.

Happy coding!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)