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

JavascriptFunctional ProgrammingEcmascript 6

Javascript Problem Overview


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' ]

Javascript Solutions


Solution 1 - Javascript

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

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

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

Solution 2 - Javascript

Array.prototype.map

Array.prototype.map already gives you the index as the second argument to the callback procedure... And it's 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, python's 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

Solution 3 - Javascript

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

Solution 4 - Javascript

Excuse me if I'm being ignorant (bit of a newbie to JavaScript here), but can't you just use forEach? e.g:

function withIndex(elements) {
    var results = [];
    elements.forEach(function(e, ind) {
        results.push(`${e}:${ind}`);
    });
    return results;
}

alert(withIndex(['a', 'b']));

There's also naomik's answer which is a better fit for this particular use case, but I just wanted to point out that forEach also fits the bill.

ES5+ supported.

Solution 5 - Javascript

pythonic offers an enumerate function that works on all iterables, not just arrays, and returns an Iterator, like python:

import {enumerate} from 'pythonic';

const arr = ['a', 'b'];
for (const [index, value] of enumerate(arr))
    console.log(`index: ${index}, value: ${value}`);
// index: 0, value: a
// index: 1, value: b

Disclosure I'm author and maintainer of Pythonic

Solution 6 - Javascript

as Kyle and Shanoor say is Array.prototype.entries()

but for newbie like me, hard to fully understand its meaning.

so here give an understandable example:

for(let curIndexValueList of someArray.entries()){
  console.log("curIndexValueList=", curIndexValueList)
  let curIndex = curIndexValueList[0]
  let curValue = curIndexValueList[1]
  console.log("curIndex=", curIndex, ", curValue=", curValue)
}

equivalent to python code:

for curIndex, curValue in enumerate(someArray):
  print("curIndex=%s, curValue=%s" % (curIndex, curValue))
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuillaume VincentView Question on Stackoverflow
Solution 1 - JavascriptKyleView Answer on Stackoverflow
Solution 2 - JavascriptMulanView Answer on Stackoverflow
Solution 3 - JavascripttavView Answer on Stackoverflow
Solution 4 - JavascriptJames KoView Answer on Stackoverflow
Solution 5 - JavascriptKeyvanView Answer on Stackoverflow
Solution 6 - JavascriptcrifanView Answer on Stackoverflow