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

Guillaume Vincent picture Guillaume Vincent · Dec 17, 2015 · Viewed 28.1k times · Source

Python has a built-in function enumerate, to get an iterable of (index, item) pairs.

Does ES6 have an equivalent for an array? What is it?

def elements_with_index(elements):
    modified_elements = []
    for i, element in enumerate(elements):
         modified_elements.append("%d:%s" % (i, element))
    return modified_elements

print(elements_with_index(["a","b"]))
#['0:a', '1:b']

ES6 equivalent without enumerate:

function elements_with_index(elements){
     return elements.map(element => elements.indexOf(element) + ':' + element);
 }

console.log(elements_with_index(['a','b']))
//[ '0:a', '1:b' ]

Answer

Kyle picture Kyle · Dec 17, 2015

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

const foobar = ['A', 'B', 'C'];

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