Welcome to today's session on "Multidimensional Arrays and Their Traversal in JavaScript". Multidimensional arrays are types of arrays that store arrays at each index instead of single elements. They allow us to create complex data structures that can model various real-life scenarios. Our goal today is to strengthen your foundational knowledge of multidimensional arrays and how to handle them effectively in JavaScript.
To construct a multidimensional array in JavaScript, we use arrays of arrays. Here is an example to demonstrate how to create and work with 2D static arrays:
JavaScript1let array = [ 2 [1, 2, 3], 3 [4, 5, 6], 4 [7, 8, 9] 5]; 6 7console.log(array); 8// Outputs: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
All indices in JavaScript arrays are 0-based. In a 1-dimensional array, the [n]
notation is used to access the (n+1)th element. For example, in the array ['a', 'b', 'c']
, to access the element 'b'
, you would use array[1]
since indices are zero-based.
For multidimensional arrays, each element is itself an array. Therefore, you can access an entire row (inner array) or a specific element within that row. Let's say you want to access the first row and the second element within that row:
JavaScript1let array = [ 2 ['a', 'b', 'c'], 3 ['d', 'e', 'f'], 4 ['g', 'h', 'i'] 5]; 6 7let row1 = array[0]; // Accessing the first row 8let item = row1[1]; // Accessing the second element in the first row 9 10console.log(item); // Outputs: 'b'
Here, row1 = array[0]
gets the first row, and item = row1[1]
gives us the element 'b'
, which is the second element in the first row. Note that this is equivalent to directly accessing (array[0])[1]
, or array[0][1]
for short:
JavaScript1let array = [ 2 ['a', 'b', 'c'], 3 ['d', 'e', 'f'], 4 ['g', 'h', 'i'] 5]; 6 7// Accessing an element directly 8console.log(array[0][1]); // Outputs: 'b'
In this case, array[0]
refers to the first inner array, and [1]
refers to the second element of that array.
It's also important to note that if you try to access an index that is out of bounds, it does not throw an error but returns undefined
:
JavaScript1let array = [ 2 ['a', 'b', 'c'], 3 ['d', 'e', 'f'], 4 ['g', 'h', 'i'] 5]; 6 7console.log(array[3]); // Outputs: undefined 8console.log(array[0][5]); // Outputs: undefined 9console.log(array[3][5]); // Throws a TypeError
In this example:
array[3]
tries to access the fourth row, which does not exist, so it returnsundefined
.array[0][5]
tries to access the sixth element in the first row, which also does not exist, so it returnsundefined
.
However, console.log(array[3][5])
attempts to access a property of undefined
, which throws a TypeError
.
Another way to look at multidimensional arrays is with an analogy. You can think of the rows as floors and the columns as apartments on each floor. By using nested loops, we can easily visit every floor (outer array) and every apartment on each floor (inner array) to perform various operations.
JavaScript1let array = [ 2 ["Apt 101", "Apt 102", "Apt 103"], 3 ["Apt 201", "Exit Floor", "Apt 203"], 4 ["Apt 301", "Apt 302", "Apt 303"] 5]; 6 7// Loop through 2D array 8for (let i = 0; i < array.length; i++) { 9 for (let j = 0; j < array[i].length; j++) { 10 console.log(array[i][j] + ", "); 11 } 12 console.log(); 13} 14 15// Outputs: 16// Apt 101, 17// Apt 102, 18// Apt 103, 19// 20// Apt 201, 21// Exit Floor, 22// Apt 203, 23// 24// Apt 301, 25// Apt 302, 26// Apt 303,
The outer loop (for (let i = 0; i < array.length; i++)
) iterates through the rows of the multidimensional array, where array.length
returns the number of rows. The inner loop (for (let j = 0; j < array[i].length; j++)
) iterates through the columns within each row, where array[i].length
returns the number of elements in the current row.
To continue with the apartment-building analogy, suppose the task is to replace an apartment number. For instance, let's update the second apartment number on the first floor (the second element in the first array) to a new number. Here's how we can achieve this:
JavaScript1let array = [ 2 ["Apt 101", "Apt 102", "Apt 103"], 3 ["Apt 201", "Apt 202", "Apt 203"], 4 ["Apt 301", "Apt 302", "Apt 303"] 5]; 6 7// Updating an element 8array[0][1] = "Apt 104"; // Changing "Apt 102" to "Apt 104" 9 10for (let i = 0; i < array.length; i++) { 11 for (let j = 0; j < array[i].length; j++) { 12 console.log(array[i][j] + " "); 13 } 14 console.log(); 15} 16 17// Outputs: 18// Apt 101 Apt 104 Apt 103 19// Apt 201 Apt 202 Apt 203 20// Apt 301 Apt 302 Apt 303
JavaScript offers various ways to manage multidimensional arrays. For instance, you can determine the number of rows (floors) and columns (units on each floor):
JavaScript1let array = [ 2 [1, 2, 3], 3 [4, 5, 6], 4 [7, 8, 9] 5]; 6 7// Finding the number of rows 8let numFloors = array.length; 9console.log(numFloors); // Outputs: 3 10 11// Finding the number of columns 12let numUnits = array[0].length; 13console.log(numUnits); // Outputs: 3
To add a new row to a 2D static array, you typically add the new row at the end of the array, as dynamically inserting rows at specific positions can be complex and is not generally recommended for static arrays. If you want to insert a new row at a specific position, keep in mind that it will involve shifting subsequent rows.
JavaScript1let array = [ 2 [1, 2, 3], 3 [4, 5, 6], 4 [7, 8, 9] 5]; 6 7array[3] = [10, 11, 12]; // Adding a new row at the 4th position 8 9for (let i = 0; i < array.length; i++) { 10 for (let j = 0; j < array[i].length; j++) { 11 console.log(array[i][j] + " "); 12 } 13 console.log(); 14} 15 16// Outputs: 17// 1 2 3 18// 4 5 6 19// 7 8 9 20// 10 11 12
To remove a column from a 2D array, you can directly modify each row using the splice
method.
JavaScript1let array = [ 2 [1, 2, 3], 3 [4, 5, 6], 4 [7, 8, 9] 5]; 6 7// Removing the second column (index 1) from each row 8for (let i = 0; i < array.length; i++) { 9 array[i].splice(1, 1); // Remove 1 element at index 1 of each row 10} 11 12for (let i = 0; i < array.length; i++) { 13 for (let j = 0; j < array[i].length; j++) { 14 console.log(array[i][j] + " "); 15 } 16 console.log(); 17} 18 19// Outputs: 20// 1 3 21// 4 6 22// 7 9
To remove a row, you can use the splice
method directly on the main array.
JavaScript1let array = [ 2 [1, 2, 3], 3 [4, 5, 6], 4 [7, 8, 9] 5]; 6 7// Removing the second row (index 1) 8array.splice(1, 1); // Remove 1 element at index 1 of the array 9 10for (let i = 0; i < array.length; i++) { 11 for (let j = 0; j < array[i].length; j++) { 12 console.log(array[i][j] + " "); 13 } 14 console.log(); 15} 16 17// Outputs: 18// 1 2 3 19// 7 8 9
In both examples, splice(1, 1)
means at index 1, remove 1 element. This removes the second column from each row in the first case, and removes the second row in the second case.
Sometimes, when we visit every apartment on each floor, we might need to start visiting the next floor midway. break
helps us exit the current loop, while continue
helps us skip the current iteration and move to the next one.
JavaScript1let array = [ 2 ["Apt 101", "Apt 102", "Apt 103"], 3 ["Apt 201", "Exit Floor", "Apt 203"], 4 ["Apt 301", "Apt 302", "Apt 303"] 5]; 6 7// Break in nested loop 8for (let i = 0; i < array.length; i++) { 9 for (let j = 0; j < array[i].length; j++) { 10 if (array[i][j] === "Exit Floor") { 11 break; 12 } 13 console.log(array[i][j] + ", "); 14 } 15 console.log(); 16} 17 18// Outputs: 19// Apt 101, 20// Apt 102, 21// Apt 103, 22// 23// Apt 201, 24// 25// Apt 301, 26// Apt 302, 27// Apt 303,
Here, as soon as Exit Floor
is found on a floor, the entire loop breaks, and no further units on this floor are visited. However, the remaining floors are processed as before, as break
breaks only the nested inner loop.
We can also make use of continue
in a similar scenario:
JavaScript1let array = [ 2 ["Apt 101", "Apt 102", "Apt 103"], 3 ["Apt 201", "Exit Floor", "Apt 203"], 4 ["Apt 301", "Apt 302", "Apt 303"] 5]; 6 7// Continue in nested loop 8for (let i = 0; i < array.length; i++) { 9 for (let j = 0; j < array[i].length; j++) { 10 if (array[i][j] === "Exit Floor") { 11 continue; 12 } 13 console.log(array[i][j] + ", "); 14 } 15 console.log(); 16} 17 18// Outputs: 19// Apt 101, 20// Apt 102, 21// Apt 103, 22// 23// Apt 201, 24// Apt 203, 25// 26// Apt 301, 27// Apt 302, 28// Apt 303,
That was exciting! We went through various operations on multidimensional arrays, starting from their creation, methods to update, and useful JavaScript methods. We also learned how we can visit every row and every element in each row.
Practice solidifies learning! Your new adventure awaits in our upcoming practical exercises, where you can apply these concepts to multidimensional arrays! Buckle up and have fun!