I am currently modifying some code and trying to not mess with the initial structure code. Having a for...of
loop over an array, and having a second array with an identical structure, I am wondering if there is a quick way to make a generator over my second array to simulate a zip.
Here’s an example:
const firstArray = ["a", "b", "c"];
const myAdditionalArray = [1, 2, 3];
// const generatorOverMyAdditionalAray = ???
for (const item of firstArray) {
// Initial code doing stuff with item
const additionalItem = myAdditionalArray.next();
// More code doing stuff with item and additionalItem
}
For pythonistas, it would look something like that
>>> a = ["a", "b", "c"]
>>> b = [1, 2, 3]
>>> generator_over_b = (x for x in b)
>>> for item in a:
... additional_item = next(generator_over_b)
... print(item, additional_item)
...
a 1
b 2
c 3
Edit: Added emphasis on why for
or forEach
loops are not a viable solution (and ultimately do not answer the question)
2
Answers
Arrays have a
values
method for getting an iterator:You could also implement a
zip
like generator, using[Symbol.iterator]
— which is the method an object should have when it is iterable:Array#values()
gives an iterator over an array:In general,
for..of
uses the iteration protocol so using it on a value will fetch an iterator using the well-known@@iterator
. For arrays, the symbol is aliased to.value
, so the two are equivalent:The
@@iterator
symbol can be used with any iterable, for example, a set:Or a string: