javascript Multi-dimensional arrays

JavaScript: Multi-Dimensional Arrays

In JavaScript, arrays are commonly used to store lists of data. However, sometimes we need to store more complex data, such as grids or matrices, which require arrays of arrays—these are known as multi-dimensional arrays.

Multi-dimensional arrays allow you to represent data in two or more dimensions. A 2D array, for example, can be thought of as a table with rows and columns, while higher-dimensional arrays can represent more complex structures, like 3D grids.

These types of arrays are useful in scenarios like:

  • Matrices: Useful for mathematical computations, such as those in linear algebra.
  • Tables or Grids: For representing structures like spreadsheets or game boards (e.g., Tic-Tac-Toe).
  • Maps or Maps of Maps: For working with hierarchical data.

In this article, you’ll learn how to:

  • Create multi-dimensional arrays.
  • Access and manipulate data within them.
  • Work with higher-dimensional arrays to organize complex data.

Understanding Multi-Dimensional Arrays

Multi-dimensional arrays are essentially arrays of arrays, where each element of the main array is itself an array. This allows us to store data in more than one dimension, making it ideal for representing grids, tables, or any other structure that requires rows and columns.

For example, a 2D array can be visualized as a grid with rows and columns. Each row in the array can be represented as an inner array, and the entire array is made up of these individual rows.

Here’s an example of a 2D array that represents a 3×3 grid (a simple matrix):

const matrix = [
  [1, 2, 3],  // First row
  [4, 5, 6],  // Second row
  [7, 8, 9]   // Third row
];

In this example:

  • The outer array contains three inner arrays (one for each row).
  • Each inner array has three elements, representing the columns of the grid.

You can think of this 2D array as a table:

1  2  3
4  5  6
7  8  9

Multi-dimensional arrays can also be used to represent higher dimensions (3D arrays, 4D arrays, etc.) by nesting arrays even further inside each other. But before diving into that, understanding how to work with basic 2D arrays is essential.

Creating Multi-Dimensional Arrays

Creating multi-dimensional arrays in JavaScript involves nesting arrays inside other arrays. Depending on the level of nesting, you can create 2D arrays, 3D arrays, or even higher-dimensional arrays.

Creating a 2D Array (Array of Arrays)

A 2D array is essentially an array where each element is another array. This is useful when you want to represent rows and columns, like a grid or matrix.

Here’s how you can create a 2D array:

const array2D = [
  [1, 2],  // First row
  [3, 4],  // Second row
  [5, 6]   // Third row
];

In this example:

  • The array2D array contains three sub-arrays.
  • Each sub-array represents a row in the matrix or grid, and each row contains two elements (representing the columns).

You can access elements in the 2D array by specifying both the row and column indices. For example, to access the element in the second row, first column:

console.log(array2D[1][0]);  // Output: 3

Creating a 3D Array (Array of Arrays of Arrays)

You can also create higher-dimensional arrays by nesting arrays inside other arrays. A 3D array is an array where each element is a 2D array. This is useful for representing more complex structures, like a cube or a multi-layered grid.

Here’s how you can create a 3D array:

const array3D = [
  [  // First layer
    [1, 2],  // First row
    [3, 4]   // Second row
  ],
  [  // Second layer
    [5, 6],  // First row
    [7, 8]   // Second row
  ]
];

In this example:

  • array3D contains two 2D arrays, which represent the layers of the 3D structure.
  • Each layer has two 1D arrays (representing rows), and each row contains two values.

To access an element from a 3D array, you need to specify the layer, row, and column indices:

console.log(array3D[1][0][1]);  // Output: 6

This will give you the element from the second layer, first row, and second column.

Creating Higher-Dimensional Arrays

By continuing the nesting process, you can create 4D arrays, 5D arrays, and beyond, by adding more levels of arrays. However, higher-dimensional arrays are rare in most use cases, and managing them can become complex.

The general idea is to keep nesting arrays within arrays, which allows you to store data in more than one dimension.

Accessing Elements in Multi-Dimensional Arrays

Accessing elements in multi-dimensional arrays is similar to accessing elements in regular arrays, but with multiple indices to specify the position. The more dimensions the array has, the more indices you will need to access the elements.

Accessing Elements in 2D Arrays

For a 2D array, you use two indices: one for the row and another for the column. This is how you can access elements in a grid or matrix-like structure.

array[row][column]

Here’s an example of how you can access elements in a 2D array:

const matrix = [
  [1, 2, 3],
  [4, 5, 6]
];

console.log(matrix[0][1]);  // Output: 2 (first row, second column)
console.log(matrix[1][0]);  // Output: 4 (second row, first column)

In this example:

  • matrix[0][1] accesses the element in the first row and the second column, which is 2.
  • matrix[1][0] accesses the element in the second row and the first column, which is 4.

Accessing Elements in Higher-Dimensional Arrays

For higher-dimensional arrays, such as 3D arrays, the process is the same, but you use three indices: one for the layer (or group), one for the row, and one for the column.

Here’s how you can access elements in a 3D array:

const array3D = [
  [[1, 2], [3, 4]],  // First group (layer)
  [[5, 6], [7, 8]]   // Second group (layer)
];

console.log(array3D[1][0][1]);  // Output: 6 (second group, first sub-array, second element)

In this example:

  • array3D[1] accesses the second group (layer) of the 3D array, which is [[5, 6], [7, 8]].
  • array3D[1][0] accesses the first sub-array in the second group, which is [5, 6].
  • array3D[1][0][1] accesses the second element in the first sub-array of the second group, which is 6.

You can extend this pattern to even higher-dimensional arrays by adding more indices. For example, to access elements in a 4D array, you would use four indices, and so on.

Iterating Over Multi-Dimensional Arrays

When working with multi-dimensional arrays, you often need to iterate through the elements. You can use loops to go through each level of the array and access its elements. Both traditional for loops and the more modern forEach() method are commonly used for this task.

Using for Loops to Iterate Through a 2D Array

A 2D array can be iterated using nested for loops. The outer loop iterates through each row, while the inner loop iterates through each element within that row.

const matrix = [
  [1, 2, 3],
  [4, 5, 6]
];

for (let i = 0; i < matrix.length; i++) {

  for (let j = 0; j < matrix[i].length; j++) {
    console.log(matrix[i][j]);
  }

}

In this example:

  • The outer loop (for (let i = 0; i < matrix.length; i++)) iterates through each row of the matrix.
  • The inner loop (for (let j = 0; j < matrix[i].length; j++)) iterates through each element within the current row.
  • matrix[i][j] gives you access to the current element.

Using forEach() to Iterate Over a 2D Array

You can also use the forEach() method to iterate over multi-dimensional arrays. This method works similarly to loops but uses callback functions for handling each item.

const matrix = [
  [1, 2, 3],
  [4, 5, 6]
];

matrix.forEach(row => {
  row.forEach(element => console.log(element));
});

In this example:

  • matrix.forEach(row => {...}) iterates through each row of the 2D array.
  • Inside the callback for each row, we use another forEach() to loop through each element of that row.

Using Loops for Higher-Dimensional Arrays

You can extend this approach to 3D arrays or higher-dimensional arrays by adding more loops. For example, for a 3D array, you’d use three nested for loops.

const array3D = [
  [[1, 2], [3, 4]],
  [[5, 6], [7, 8]]
];

for (let i = 0; i < array3D.length; i++) {

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

    for (let k = 0; k < array3D[i][j].length; k++) {
      console.log(array3D[i][j][k]);
    }

  }

}

In this example:

  • The first loop iterates through each group (layer) of the 3D array.
  • The second loop iterates through each row within the group.
  • The third loop iterates through each element within the row.

This approach can be adapted to any higher-dimensional arrays by adding additional nested loops.

Modifying Elements in Multi-Dimensional Arrays

Modifying elements in multi-dimensional arrays is similar to modifying elements in a regular 1D array. You access the elements using multiple indices (one for each level of the array), and you can directly assign new values to those elements.

Changing Individual Elements

To modify an element in a 2D array or higher-dimensional array, you simply access the desired element by specifying its row (and column, and additional dimensions if applicable) and assign a new value to it.

const matrix = [
  [1, 2, 3],
  [4, 5, 6]
];

matrix[0][1] = 20; // Changing the second element of the first row
console.log(matrix); // [[1, 20, 3], [4, 5, 6]]

In this example:

  • Here, matrix[0][1] accesses the second element of the first row (2), and we change it to 20.
  • The output shows the updated matrix, where the second element of the first row has been modified.

Modifying Elements in Higher-Dimensional Arrays

For 3D arrays or more complex multi-dimensional arrays, the process is the same, but you need to access each dimension with the appropriate index.

const array3D = [
  [[1, 2], [3, 4]],
  [[5, 6], [7, 8]]
];

array3D[1][0][1] = 100; // Changing the second element of the first row in the second group
console.log(array3D); // [[[1, 2], [3, 4]], [[5, 100], [7, 8]]]

In this example:

  • array3D[1][0][1] accesses the second element of the first row in the second group (6), and we change it to 100.
  • The updated 3D array shows the modified value.

You can modify any element in a multi-dimensional array by accessing it through its index(es) and assigning a new value. The approach works for arrays of any dimension—just continue to specify the indices for each dimension level.

Adding and Removing Rows or Columns

Adding or removing rows and columns in a multi-dimensional array (specifically in a 2D array) is a common task. JavaScript provides easy ways to manipulate arrays and adjust their dimensions.

Adding a New Row

To add a new row to a 2D array, you can use the push() method. This method adds an element (in this case, a new row) to the end of the array.

const matrix = [
  [1, 2],
  [3, 4]
];

matrix.push([5, 6]); // Adds a new row

console.log(matrix); // [[1, 2], [3, 4], [5, 6]]

In this example:

  • Here, matrix.push([5, 6]) adds the new row [5, 6] to the end of the matrix.
  • The resulting array now has three rows.

Adding a New Column

To add a new column to each row in a 2D array, you can use the forEach() method in combination with push(). This will add a new element to each row of the array, thus expanding the matrix horizontally.

const matrix = [
  [1, 2],
  [3, 4],
  [5, 6]
];

matrix.forEach(row => row.push(0)); // Adding a column with 0 values

console.log(matrix); // [[1, 2, 0], [3, 4, 0], [5, 6, 0]]

In this example:

  • matrix.forEach(row => row.push(0)) iterates through each row and adds a 0 to the end of each row, effectively adding a new column.
  • The matrix now has three columns.

Removing Rows or Columns

Removing rows or columns can also be done easily.

Removing a row: You can use the pop() method to remove the last row or shift() to remove the first row.

matrix.pop(); // Removes the last row
console.log(matrix); // [[1, 2, 0], [3, 4, 0]]

Removing a column: To remove a column, you can loop through each row and use pop() to remove the last element (column) or use shift() to remove the first column.

matrix.forEach(row => row.pop()); // Removes the last column from each row
console.log(matrix); // [[1, 2], [3, 4], [5, 6]]

You can add rows using push(), and add columns using forEach() combined with push(). Similarly, you can remove rows with pop() or shift(), and remove columns by iterating through each row and using pop() or shift() on the rows.

Working with Jagged Arrays (Arrays with Different Lengths)

In JavaScript, arrays do not have to be uniform in size. A jagged array (also known as an irregular array) is an array where each sub-array can have a different length. This allows for more flexible data structures, particularly when working with data that does not fit into a regular grid or matrix.

What is a Jagged Array?

A jagged array is essentially an array of arrays where the inner arrays can vary in length. This flexibility can be useful in cases where each “row” or “sub-array” represents a set of values with a different number of elements.

const jaggedArray = [
  [1, 2, 3],   // First row with 3 elements
  [4, 5],       // Second row with 2 elements
  [6, 7, 8, 9]  // Third row with 4 elements
];

console.log(jaggedArray[1][1]); // 5 (second row, second column)

In this example:

  • The jaggedArray above contains three sub-arrays (rows), each with a different number of elements. The first row has 3 elements, the second has 2, and the third has 4.
  • The value jaggedArray[1][1] refers to the second row and the second element, which is 5.

Accessing Elements in Jagged Arrays

Just like with regular multi-dimensional arrays, elements in a jagged array can be accessed using multiple indices. However, because the inner arrays may have different lengths, you need to be mindful of which index you are accessing within each sub-array.

console.log(jaggedArray[0][2]); // 3 (first row, third column)
console.log(jaggedArray[2][3]); // 9 (third row, fourth column)

Iterating Over Jagged Arrays

To iterate over a jagged array, you can use nested loops or methods like forEach(). The important thing to note is that the inner arrays might have different lengths, so you may want to ensure you’re iterating within the bounds of each individual sub-array.

Example of iterating with forEach():

jaggedArray.forEach(row => {
  row.forEach(element => console.log(element));
});

This will print all the elements from the jagged array, one by one.

A jagged array is an array where each sub-array can have a different number of elements. You access elements in a jagged array in the same way as regular multi-dimensional arrays, but be aware that the inner arrays may vary in length. When iterating, it’s important to account for the possibility of different sub-array lengths to avoid errors or unintended results.

Multi-Dimensional Arrays in Functions

In JavaScript, multi-dimensional arrays can be passed to functions just like any other type of array. When you pass an array to a function, it is passed by reference, meaning the function can modify the original array if needed. This concept allows you to manipulate multi-dimensional arrays in various ways inside functions.

Passing Multi-Dimensional Arrays to Functions

When you pass a multi-dimensional array to a function, you can access and modify its elements inside the function. The array remains the same outside the function, unless you explicitly modify it within the function.

Example: Passing a 2D Array to a Function

Let’s say you have a function that prints the rows of a matrix (2D array). You can pass the matrix as an argument to the function and iterate over it to display its contents.

function printMatrix(matrix) {

  matrix.forEach(row => {
    console.log(row.join(' ')); // Join each row's elements into a string with spaces
  });

}

const matrix = [
  [1, 2, 3],
  [4, 5, 6]
];

printMatrix(matrix); 

In this example:

  • The function printMatrix() takes a 2D array matrix as a parameter.
  • The function uses the forEach() method to loop over each row in the matrix.
  • For each row, join(' ') is used to convert the elements into a string separated by spaces, which is then printed to the console.

Modifying Multi-Dimensional Arrays Inside Functions

Since arrays are passed by reference in JavaScript, you can also modify the elements of a multi-dimensional array within a function. For example:

function modifyMatrix(matrix) {
  matrix[0][0] = 100; // Modify the first element of the first row
}

const matrix = [
  [1, 2, 3],
  [4, 5, 6]
];

modifyMatrix(matrix);

console.log(matrix); 

In this example:

  • The modifyMatrix() function changes the first element of the first row (matrix[0][0]) to 100.
  • Since the array is passed by reference, the original matrix is modified, and the change is reflected outside the function as well.

Returning Multi-Dimensional Arrays from Functions

You can also return multi-dimensional arrays from functions. For example, let’s write a function that creates a new 2D array based on some conditions:

function createMatrix(rows, cols) {

  let matrix = [];

  for (let i = 0; i < rows; i++) {

    let row = [];

    for (let j = 0; j < cols; j++) {
      row.push(i * j); // Fill the matrix with products of row and column indices
    }

    matrix.push(row);

  }

  return matrix;

}

const newMatrix = createMatrix(3, 3);

console.log(newMatrix);

In this example:

  • The createMatrix() function creates a 2D array where each element is the product of its row and column indices.
  • The function returns the newly created 2D array, which is then stored in newMatrix and logged to the console.

Multi-dimensional arrays can be passed to functions as arguments and modified inside the function. JavaScript arrays are passed by reference, so changes to the array within a function will affect the original array. You can also return multi-dimensional arrays from functions, allowing you to dynamically create and manipulate arrays.

Conclusion

In this article, we’ve explored the core concepts of working with multi-dimensional arrays in JavaScript. Here’s a quick recap:

  • Creating Multi-Dimensional Arrays: We learned how to create arrays with multiple dimensions, including 2D and 3D arrays, which allow us to organize data in grids, matrices, or even higher-dimensional structures.
  • Accessing Elements: We saw how to access specific elements within multi-dimensional arrays by using multiple indices, which helps pinpoint data in complex structures.
  • Modifying Elements: Modifying individual elements within a multi-dimensional array is straightforward by accessing elements with their indices and updating them as needed.
  • Iterating Over Arrays: We explored different looping techniques like for loops and forEach() to iterate through multi-dimensional arrays and perform operations on each element.
  • Adding/Removing Rows/Columns: We discussed how to dynamically add new rows or columns to a 2D array, making multi-dimensional arrays flexible for changes.
  • Working with Jagged Arrays: Jagged arrays (arrays with rows of varying lengths) were introduced, showing how JavaScript allows for flexible array structures.
  • Using Multi-Dimensional Arrays in Functions: We also explored passing multi-dimensional arrays to functions for manipulation, and how you can modify or return them from within functions.

Multi-dimensional arrays are incredibly useful for representing complex data structures such as grids, matrices, or even tables. They are essential when you need to store and process data in multiple dimensions.

As you dive deeper into JavaScript, don’t hesitate to experiment with multi-dimensional arrays to represent real-world data in your applications. Whether you’re working with game boards, charts, or any other complex data structure, these arrays are a powerful tool for organizing and manipulating your data effectively.

Remember, mastering multi-dimensional arrays will help you handle more sophisticated data structures and pave the way for more advanced problem-solving techniques in JavaScript.

Scroll to Top