Languages
[Edit]
EN

TypeScript - foreach with index

8 points
Created by:
Paluskitten
356

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.

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.

TypeScript

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