JavaScript is a versatile and powerful language, often used for both client-side and server-side development. One of the many data structures it supports is the 2D array, also known as a matrix or a two-dimensional array. This article will delve into the details of 2D arrays in JavaScript, including their creation, manipulation, and common operations.
Introduction to 2D Arrays
A 2D array is essentially an array of arrays. It is useful for representing data in a grid-like structure, such as a table or a matrix. Each element in the main array is itself an array, and each of these sub-arrays can hold a series of values.
Creating 2D Arrays
There are several ways to create a 2D array in JavaScript. Here are some common methods:
Using Nested Arrays
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix);
Using Loops
let rows = 3;
let cols = 3;
let matrix = new Array(rows);
for (let i = 0; i < rows; i++) {
matrix[i] = new Array(cols).fill(0);
}
console.log(matrix);
Accessing Elements in a 2D Array
Accessing elements in a 2D array requires specifying both the row and column indices.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]); // Output: 6
Iterating Over 2D Arrays
To process or traverse a 2D array, nested loops are typically used.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}
Modifying Elements in a 2D Array
Modifying elements involves accessing the specific index and assigning a new value.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
matrix[1][2] = 10;
console.log(matrix[1][2]); // Output: 10
Common Operations on 2D Arrays
Transposing a Matrix
Transposing a matrix involves swapping rows and columns.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let transposed = matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex]));
console.log(transposed);
Flattening a 2D Array
Flattening a 2D array converts it into a 1D array.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let flattened = matrix.reduce((acc, curr) => acc.concat(curr), []);
console.log(flattened); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Finding the Sum of All Elements
Calculating the sum of all elements in a 2D array can be done using nested loops.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let sum = 0;
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
}
console.log(sum); // Output: 45
Matrix Multiplication
Matrix multiplication involves multiplying two matrices.
let A = [
[1, 2],
[3, 4]
];
let B = [
[5, 6],
[7, 8]
];
let result = new Array(A.length).fill(0).map(() => new Array(B[0].length).fill(0));
for (let i = 0; i < A.length; i++) {
for (let j = 0; j < B[0].length; j++) {
for (let k = 0; k < B.length; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
console.log(result);
Practical Examples
Example 1: Rotating a 2D Array
Rotating a matrix 90 degrees clockwise can be achieved by transposing and then reversing each row.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let rotated = matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex])).map(row => row.reverse());
console.log(rotated);
Example 2: Spiral Order Traversal
Printing a 2D array in spiral order.
function spiralOrder(matrix) {
let result = [];
while (matrix.length) {
result = result.concat(matrix.shift());
for (let i = 0; i < matrix.length; i++) {
result.push(matrix[i].pop());
}
matrix.reverse().map(row => row.reverse());
}
return result;
}
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(spiralOrder(matrix)); // Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Conclusion
Understanding and working with 2D arrays in JavaScript opens up a multitude of possibilities for handling complex data structures. This guide covered the basics of creating, accessing, iterating over, and performing various operations on 2D arrays. With these fundamentals, you can tackle more advanced topics and applications, making your JavaScript programming more robust and versatile.