Array.entries()
The Array.entries()
method in JavaScript returns a new Array Iterator
object that contains key/value pairs for each index in the array. The keys are the array indices, and the values are the corresponding array elements.
Syntax
</>
Copy
array.entries()
Parameters
The entries()
method does not take any parameters.
Return Value
The entries()
method returns a new Array Iterator
object. Each item in the iterator is a two-element array, where the first element is the array index (key) and the second element is the array value.
Examples
1. Iterating Over an Array with entries()
This example demonstrates how to use the entries()
method to iterate over an array’s key-value pairs.
</>
Copy
const fruits = ["apple", "banana", "cherry"];
const iterator = fruits.entries();
for (const [index, value] of iterator) {
console.log(index, value);
}
Output
0 apple
1 banana
2 cherry
iterator
provides key-value pairs from the array.- Using
for...of
, each index and value pair is destructured and logged to the console.
2. Converting an Iterator to an Array
The returned iterator can be converted into an array using the Array.from()
method.
</>
Copy
const fruits = ["apple", "banana", "cherry"];
const entriesArray = Array.from(fruits.entries());
console.log(entriesArray);
Output
[ [ 0, 'apple' ], [ 1, 'banana' ], [ 2, 'cherry' ] ]
Array.from()
converts the iterator returned byentries()
into an array of key-value pairs.- Each sub-array contains the index as the first element and the value as the second.
3. Using entries()
in a Map-Like Structure
The entries()
method can be useful when treating arrays like maps or dictionaries.
</>
Copy
const scores = [10, 20, 30];
for (const [key, value] of scores.entries()) {
console.log(`Player ${key + 1}: ${value} points`);
}
Output
Player 1: 10 points
Player 2: 20 points
Player 3: 30 points
- The
entries()
method returns each index-value pair. - The
for...of
loop is used to format and log the output for each player.