Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

TypeScript - foreach with index

0 contributions
8 points

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.

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more