What is the idiomatic way to loop over a Javascript array multiple elements at a time?

Viewed 99

In Python, you can do the following:

>>> foo = ["some", "random", "list", "foo"]
>>> for a, b, c in zip(foo, foo[1:], foo[2:]):
...     print(f"{a} {b} {c}")
... 
some random list
random list foo

How can I do the same thing in Javascript without having to use a positional index in the loop? Or is that the idiomatic way?

1 Answers

You could take a generator and get the parts.

function* zip(array, n) {
    let i = 0;
    while (i + n <= array.length) {
        yield array.slice(i, i + n);
        i++;
    }
}

let foo = ["some", "random", "list", "foo"];

for (let [a, b, c] of zip(foo, 3))
    console.log(a, b, c);

Related