Search code examples
javascriptloopsidiomsecmascript-2016

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


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?


Solution

  • 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);