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.
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.forEachmethod 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-ofloop 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-inloop with array is risky because of possible additional array properties -array.hasOwnProperty(key)method solves the problem.