Languages
[Edit]
EN

JavaScript - foreach array of arrays

0 points
Created by:
Olivier-Myers
514

In this article, we would like to show you how to use a nested for-each loop to iterate an array of arrays in JavaScript.

1. forEach method example

This section shows how to use forEach method to iterate over an array of arrays.

// ONLINE-RUNNER:browser;

let array = [['item 1', 'item 2'],['item 3', 'item 4']];

array.forEach((child) => {
  child.forEach((item, index) => {
    console.log('child index ' + index + ': ' + item);
  })
});

Note: Array.prototype.forEach method was introduced in ES5 (ECMAScript 2009).

2. for-of  loop example

This section shows how to use for-of loop construction to iterate over an array of arrays.

// ONLINE-RUNNER:browser;

let array = [['item 1', 'item 2'],['item 3', 'item 4']];

for(let child of array) {
  for(let item of child){
    console.log(item);
  }
}

Note: for-of loop was introduced in ES6 (ECMAScript 2015).

3. for-in loop example

This section shows how to use for-in loop construction to iterate over an array of arrays.

// ONLINE-RUNNER:browser;

let array = [['item 1', 'item 2'],['item 3', 'item 4']];

for(var key1 in array) {
  if(array.hasOwnProperty(key1)) {
    let child = array[key1];
    for(var key2 in child) {
      if(child.hasOwnProperty(key2)) {
        console.log(child[key2]);
      }
    }
  }
}

Note: using for-in loop with array is risky because of possible additional array properties - array.hasOwnProperty(key) method solves the problem.

References

Alternative titles

  1. Javascript - foreach nested array example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join