EN
TypeScript - foreach array of arrays
3 points
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.
This section shows how to use forEach
method to iterate over an array of arrays.
xxxxxxxxxx
1
const array: string[][] = [
2
['item 1', 'item 2'],
3
['item 3', 'item 4'],
4
];
5
6
array.forEach((items: string[], index1: number): void => {
7
items.forEach((item: string, index2: number): void => {
8
console.log(item);
9
});
10
});
Output:
xxxxxxxxxx
1
item 1
2
item 2
3
item 3
4
item 4
Note:
Array.prototype.forEach
method was introduced in ES5 (ECMAScript 2009).
This section shows how to use for-of
loop construction to iterate over an array of arrays.
xxxxxxxxxx
1
const array: string[][] = [
2
['item 1', 'item 2'],
3
['item 3', 'item 4'],
4
];
5
6
for (const items of array) {
7
for (const item of items) {
8
console.log(item);
9
}
10
}
Output:
xxxxxxxxxx
1
item 1
2
item 2
3
item 3
4
item 4
Note:
for-of
loop was introduced in ES6 (ECMAScript 2015).
This section shows how to use for-in
loop construction to iterate over an array of arrays.
xxxxxxxxxx
1
const array: string[][] = [
2
['item 1', 'item 2'],
3
['item 3', 'item 4'],
4
];
5
6
for (const key1 in array) {
7
if (array.hasOwnProperty(key1)) {
8
const items = array[key1];
9
for (const key2 in items) {
10
if (items.hasOwnProperty(key2)) {
11
console.log(items[key2]);
12
}
13
}
14
}
15
}
Output:
xxxxxxxxxx
1
item 1
2
item 2
3
item 3
4
item 4
Note: using
for-in
loop with array is risky because of possible additional array properties -array.hasOwnProperty(key)
method solves the problem.