1

In python there is a nice shortcut to get the index and element of an interable:

>>> arr=['a','b','c']
>>> for idx, arr in enumerate(arr):
...    print (idx, arr)
...
(0, 'a')
(1, 'b')
(2, 'c')

Would the following be the same in javascript, or would it need to be a generator function instead?

function enumerate1(arr) {
    let out = [];
    for (let idx=0; idx<arr.length; idx++) {
        let elem = arr[idx];
        out.push([idx, elem]);
    }
    return out;
}
let arr1 = ['a','b','c'];
for (let [idx, elem] of enumerate1(arr1)) {
    console.log(idx, elem);
}

// or, a bit more concise
let arr2 = ['a','b','c'];
const enumerate2 = (arr) => arr.map((idx, elem) => [idx, elem]);
for (let [idx, elem] of enumerate2(arr2)) {
    console.log(idx, elem);
}
David542
  • 104,438
  • 178
  • 489
  • 842
  • You could certainly use a generator for this if you wanted, or `for (const [index, value] of theArray.entries())` directly. – T.J. Crowder Mar 18 '22 at 17:46
  • 1
    Not sure why this has been closed, as this question is different than the linked duplicate. Try `arr.forEach((element, index) => console.log(element, index))` – Nolan B. Mar 18 '22 at 17:48
  • 2
    @NolanB. - ...which is one of the many solutions provided by the linked answers, which is why it's a duplicate (by SO's rules for duplicates). :-) – T.J. Crowder Mar 18 '22 at 17:49

0 Answers0