點燈坊

失くすものさえない今が強くなるチャンスよ

Using entries to get Index and Element from Array

Sam Xiao's Avatar 2021-11-21

ECMAScript 2015 introduced Array.prototype.entries, which returns index and element from Array.

Version

ECMAScript 2015

Definition

For Of Loop

let data = ['Sam', 'Kevin', 'Jimmy']

for (let [i, x] of data.entries())
  console.log (`${i}: ${x}`)

entries returns Array Iterator, we can use Array Destructuring to destructure it to get index and element.

entries000

map

let data = ['Sam', 'Kevin', 'Jimmy']

let f = a => Array.from (a.entries ())
  .map (([i, x]) => `${i}: ${x}`)

f (data) // ?
  • entries return Array Iterator, not Array, so we can’t use map after entries
  • We have to use Array.from to transform Array Iterator to Nested Array, and then we can use map

entries001

Conclusion

  • entries return Array Iterator, not Nested Array, so we have to use Array.from to transform Array Iterator to Nested Array to use map

Reference

MDN, Array.entries