javascript – What is the ES6 equivalent of Python enumerate for a sequence?

javascript – What is the ES6 equivalent of Python enumerate for a sequence?

Yes there is, check out Array.prototype.entries().

const foobar = [A, B, C];

for (const [index, element] of foobar.entries()) {
  console.log(index, element);
}

Array.prototype.map

Array.prototype.map already gives you the index as the second argument to the callback procedure… And its supported almost everywhere.

[a,b].map(function(element, index) { return index + : + element; });
//=> [0:a, 1:b]

I like ES6 too

[a,b].map((e,i) => `${i}:${e}`)
//=> [0:a, 1:b]

make it lazy

However, pythons enumerate is lazy and so we should model that characteristic as well –

function* enumerate (it, start = 0)
{ let i = start
  for (const x of it)
    yield [i++, x]
}

for (const [i, x] of enumerate(abcd))
  console.log(i, x)
0 a
1 b
2 c
3 d

Specifying the second argument, start, allows the caller to control the transform of the index –

for (const [i, x] of enumerate(abcd, 100))
  console.log(i, x)
100 a
101 b
102 c
103 d

javascript – What is the ES6 equivalent of Python enumerate for a sequence?

let array = [1, 3, 5];
for (let [index, value] of array.entries()) 
     console.log(index + = + value);

Leave a Reply

Your email address will not be published. Required fields are marked *