Skip to content
the poor coder

javascript multidimensional array foreach

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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:

Text

for(var i=0; i

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

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC