TypeScript Array entries() Method
Last Updated :
19 Jul, 2024
Improve
The Array.prototype.entries() method in TypeScript returns a new array iterator object that contains the key/value pairs for each index in the array. This method is useful when you need to iterate over the key/value pairs in the array.
Note: In TypeScript, the entries() method is not available directly on arrays as it is in JavaScript for objects, but we can achieve a similar result through a different approach.
Syntax:
Object.entries(arrayName)
Return Value:
- An iterator that yields key-value pairs, where keys are indices and values are array elements.
Examples of Array entries() Method
Example 1: Accessing Student Names and Indices Using entries()
In this example, we will use the entries() method to iterate over the student names array and access their indices and values.
const students: string[] = ["Pankaj", "Ram", "Shravan"];
const iterator = students.entries();
for (let entry of iterator) {
const [index, value] = entry;
console.log(`Index: ${index}, Value: ${value}`);
}
Output:
Index: 0, Value: Pankaj
Index: 1, Value: Ram
Index: 2, Value: Shravan
Example 2: Accessing Number Array Elements with Indices Using a While Loop
In this example, we will use the entries() method and a while loop to iterate over a number array and access their indices and values.
const numbers: number[] = [10, 20, 30];
const iterator = numbers.entries();
let result = iterator.next();
while (!result.done) {
const [index, value] = result.value;
console.log(`Index: ${index}, Value: ${value}`);
result = iterator.next();
}
Output:
Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Supported Browsers:
- Google Chrome
- Edge
- Firefox
- Opera
- Safari