JavaScript Array entries() method


The entries() method in JavaScript is used to create a new array iterator object that contains the key-value pairs for each index in the array. Each entry is an array where the first element is the index (key) and the second element is the corresponding value.

Syntax:

let arrayIterator = array.entries();

Return Value:

  • A new Array Iterator object that contains key-value pairs for each index in the array.

Key Points:

  • The entries() method does not modify the original array.
  • It is particularly useful when you need to access both the indices and the values of an array simultaneously.
  • The resulting iterator can be traversed using methods like next(), or it can be used in a loop (such as a for...of loop) to iterate over the entries.

Example 1: Basic usage

let array = ['a', 'b', 'c']; let iterator = array.entries(); console.log(iterator.next().value); // [0, 'a'] console.log(iterator.next().value); // [1, 'b'] console.log(iterator.next().value); // [2, 'c']

Example 2: Using a for...of loop

let array = ['x', 'y', 'z']; for (let [index, value] of array.entries()) { console.log(index, value); } // Output: // 0 'x' // 1 'y' // 2 'z'

Example 3: Converting to an Array

You can also convert the iterator into an array if needed:

let array = [10, 20, 30]; let entriesArray = Array.from(array.entries()); console.log(entriesArray); // [[0, 10], [1, 20], [2, 30]]

Example 4: Nested Arrays

If you have nested arrays, entries() will still work as expected:

let nestedArray = [[1, 2], [3, 4], [5, 6]]; let iterator = nestedArray.entries(); for (let entry of iterator) { console.log(entry); } // Output: // [0, [1, 2]] // [1, [3, 4]] // [2, [5, 6]]

Summary:

  • The entries() method is a useful tool for iterating over arrays when both the index and the corresponding value are needed.
  • It returns an iterator, making it flexible for use in various contexts, such as loops and transformations.
  • This method can enhance code clarity and simplify operations that require knowledge of both indices and values in an array.