javascript multidimensional array foreach

Understanding Multidimensional Arrays in JavaScript

As a developer, you might have come across the term 'multidimensional array' in JavaScript. In simple terms, a multidimensional array is an array that contains other arrays as its elements. For instance, an array of arrays can be created as shown below:


var multiArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

Using forEach with Multidimensional Arrays

One common task developers perform is looping through the elements of a multidimensional array. To achieve this, we can use the forEach method that is available on arrays in JavaScript.

Let's assume we want to loop through the elements of the above multidimensional array and output them to the console:


multiArray.forEach(function(innerArray) {
  innerArray.forEach(function(element) {
    console.log(element);
  });
});

The code above loops through each inner array in the multidimensional array using the outer forEach method. For each inner array, it then uses another forEach method to loop through its elements and output them to the console.

Other Methods for Looping through Multidimensional Arrays

Aside from using the forEach method, there are other methods available in JavaScript that can be used to loop through multidimensional arrays. These include:

  • for loops
  • map method
  • reduce method

For instance, we can rewrite the code above using a for loop as shown below:


for(var i=0; i

Similarly, we can use the map and reduce methods as shown below:


multiArray.map(function(innerArray) {
  innerArray.map(function(element) {
    console.log(element);
  });
});

multiArray.reduce(function(acc, innerArray) {
  return acc.concat(innerArray);
}, []).forEach(function(element) {
  console.log(element);
});

As shown above, there are several ways to loop through a multidimensional array in JavaScript. Choose the one that suits your needs best.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe