Languages
[Edit]
EN

TypeScript - foreach array of arrays

3 points
Created by:
James-Z
767

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

1. forEach method example

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

const array: string[][] = [
    ['item 1', 'item 2'],
    ['item 3', 'item 4'],
];

array.forEach((items: string[], index1: number): void => {
    items.forEach((item: string, index2: number): void => {
        console.log(item);
    });
});

Output:

item 1
item 2
item 3
item 4

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.

const array: string[][] = [
    ['item 1', 'item 2'],
    ['item 3', 'item 4'],
];

for (const items of array) {
    for (const item of items) {
        console.log(item);
    }
}

Output:

item 1
item 2
item 3
item 4

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.

const array: string[][] = [
    ['item 1', 'item 2'],
    ['item 3', 'item 4'],
];

for (const key1 in array) {
    if (array.hasOwnProperty(key1)) {
        const items = array[key1];
        for (const key2 in items) {
            if (items.hasOwnProperty(key2)) {
                console.log(items[key2]);
            }
        }
    }
}

Output:

item 1
item 2
item 3
item 4

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

Alternative titles

  1. TypeScript - 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