Languages
[Edit]
EN

TypeScript - foreach with index

8 points
Created by:
Kate_C
2854

In TypeScript it is possible to create foreach with index in following ways.

1. Array.forEach method example

let array : Array<string> = ['a', 'b', 'c'];

array.forEach((item: string, index: number): void => {
    console.log(`${index} : ${item}`);
});

Output:

0 : a
1 : b
2 : c

Run it online here.

2. Index variable with foreach example

let array : Array<string> = ['a', 'b', 'c'];
let index = 0;

for(let entry of array) {
    console.log(`${index++} : ${entry}`);
}

Output:

0 : a
1 : b
2 : c

Run it online here.

3. Array.map method example 

class Entry<T> {
    public constructor(public index: number, public item: T) {
        // nothing here...
    }
}

function mapArray<T>(array: Array<T>): Array<Entry<T>> {
    let result = array.map((item: T, index: number): Entry<T> => {
        return new Entry<T>(index, item);
    });

    return result;
}

Example:

let array : Array<string> = ['a', 'b', 'c'];

for(let {index, item} of mapArray(array)) {
    console.log(`${index} : ${item}`);
}

Output:

0 : a
1 : b
2 : c

Run it online here.

4. yield based conversion example

class Entry<T> {
    public constructor(public index: number, public item: T) {
        // nothing here...
    }
}

function* mapArray<T>(array: Array<T>): IterableIterator<Entry<T>> {
    for(let i = 0; i < array.length; ++i)
        yield new Entry(i, array[i]);
}

Example:

let array : Array<string> = ['a', 'b', 'c'];

for(let {index, item} of mapArray(array)) {
    console.log(`${index} : ${item}`);
}

Compiling and running:

$ tsc -t ES6 Script.ts
$ node Script.js

Output:

0 : a
1 : b
2 : c

Run it online here

Note: for yield keyword support --downlevelIteration parameter during compilation is necessary.

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.