Using the enumerate() Function enumerate() allows us to iterate through a sequence but it keeps track of both the index and the element. enumerate(iterable, start=0) The enumerate() function takes in an iterable as an argument, such as a list, string, tuple, or dictionary.
In Javascript, we can implement the enumerate function using the iterator and the yield keyword (the asteroid star immediate after function keyword indicates that the function should return an iterator via the yield keyword). As you can see, the incrementing index is coupled with the element in the original list/array.
The closest equivalent in all cases of what is passed to list() would be using the spread syntax from ES6. For older versions of JavaScript, you can use string. split('') for a character array.
The enumerate() is a constructor method returns an object of the enumerate class for the given iterable, sequence, iterator, or object that supports iteration. The returned enumerate object contains tuples for each item in the iterable that includes an index and the values obtained from iterating over iterable.
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 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
let array = [1, 3, 5];
for (let [index, value] of array.entries())
console.log(index + '=' + value);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With