JS: Array.prototype.entries

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2015)

xArray.entries()
  • Return a Generator.
  • Each yield is an array of the form [index, value].
console.log(
  JSON.stringify(Array.from(["a", "b", "c"].entries())) ===
    `[[0,"a"],[1,"b"],[2,"c"]]`,
);

Example. Convert array to Map with index

〔see Map Object

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

〔see Spread Operator

Verify Result is a Generator

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

// is iterable
console.log(Reflect.has(xx, Symbol.iterator));

// is iterator
console.log(Reflect.has(xx, "next"));

Array Iterator