Languages
[Edit]
EN

JavaScript - foreach array of arrays

0 points
Created by:
Dirask Community
5610

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

1. forEach method example

This section shows how to use forEach method to iterate over 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 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 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

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