.forEach
already has the capability:
const myArray = [9, 2, 5];
myArray.forEach((val, idx) => {
console.log(idx); // 0, 1, 2
console.log(val); // 9, 2, 5
});
If you prefer the features of for...of
, you can use map
on the array to retrieve the index and value:
for (const { idx, val } of myArray.map((val, idx) => ({ idx, val }))) {
console.log(idx); // 0, 1, 2
console.log(val); // 9, 2, 5
}
If this seems lengthy, consider encapsulating it in a reusable function:
function extractEntries<T>(arr: T[]) {
return arr.map((val, idx) => [idx, val] as const);
}
for (const [idx, val] of extractEntries(myArray)) {
// ..etc..
}
Iterable Approach
This approach is functional for ES3 or ES5 if compiled with the --downlevelIteration
flag.
function* extractEntries<T>(values: T[] | IterableIterator<T>) {
let idx = 0;
for (const val of values) {
yield [idx, val] as const;
idx++;
}
}
Array.prototype.entries() - For ES6+
In ES6+ environments, utilize the .entries()
method detailed in this post.