JS: Array.prototype.entries

By Xah Lee. Date: . Last updated: .

New in JS2015.

arrayX.entries()
Return a Iterator (also is a Iterable Object), each yield is an array of the form [index, value].
for (let e of ["a", "b", "c"].entries()) {
 console.log( e );
}

// prints
// [ 0, 'a' ]
// [ 1, 'b' ]
// [ 2, 'c' ]
for (let [i,k] of ["a", "b", "c"].entries()) {
 console.log( i, k );
}

// prints

// 0 'a'
// 1 'b'
// 2 'c'

Convert array to Map with index:

[see Map Object]

// convert array to map
const aa = ["a", "b", "c"];
const mm = new Map([...aa.entries()]);
console.log( mm );
// Map { 0 => 'a', 1 => 'b', 2 => 'c' }

[see Spread Operator]

This example shows the result is iterator and iterable:

const et = ["a", "b", "c"].entries();

// is a iterator
console.log(
 Object.prototype.toString .call (et) === "[object Array Iterator]"
); // true

// is also a iterable
console.log(
 Symbol.iterator in et
); // true
BUY ΣJS JavaScript in Depth