JavaScript: How to iterate through 2 arrays in parallel

Updated: March 8, 2023 By: Goodman Post a comment

Iterating through 2 arrays in parallel means iterating over 2 arrays at the same time and accessing the corresponding elements of each array. This article will show you how to do that in JavaScript.

Using a Loop

Let’s say you have 2 arrays of the same length, array1, and array2. To iterate over them in parallel, you can do as shown below:

let array1 = [1, 2, 3];
let array2 = ['A', 'B', 'C'];

for (let i = 0; i < array1.length; i++) {
  console.log(array1[i], array2[i]);
}

Output:

1 A
2 B
3 C

You can also use a forEach loop like this:

let array1 = [1, 2, 3];
let array2 = ['A', 'B', 'C'];

array1.forEach((element, index) => {
  console.log(element, array2[index]);
});

Defining a custom zip() function

If you’ve worked with Python, you’re very likely to know a built-in function named zip(). It takes multiple iterable objects (e.g. lists, tuples) and returns an iterator that aggregates the elements from each of the iterables as tuples. In other words, the function can help us easily iterate over multiple lists (arrays) in parallel.

Unfortunately, JavaScript doesn’t support a similar function as Python’s zip(). However, we can define it on our own:

function* zip(arrays) {
  let iterators = arrays.map(a => a[Symbol.iterator]());
  while (true) {
    let results = iterators.map(it => it.next());
    if (results.some(r => r.done)) return;
    yield results.map(r => r.value);
  }
}

Here’s a complete example:

// define the zip() function
function* zip(arrays) {
  let iterators = arrays.map(a => a[Symbol.iterator]());
  while (true) {
    let results = iterators.map(it => it.next());
    if (results.some(r => r.done)) return;
    yield results.map(r => r.value);
  }
}

// use the zip() function
let array1 = [1, 2, 3];
let array2 = ["dog", "cat", "mouse"];

for (let [x, y] of zip([array1, array2])) {
  console.log(x, y);
}

Output:

1 dog
2 cat
3 mouse

We can also loop through an arbitrary number of arrays in parallel with our zip() function:

let array1 = [1, 2, 3];
let array2 = ["dog", "cat", "mouse"];
let array3 = [true, false, true];

for (let [x, y, z] of zip([array1, array2, array3])) {
  console.log(x, y, z);
}

Output:

1 dog true
2 cat false
3 mouse true

Use Cases

Why and when we might need to iterate through multiple JavaScript arrays in parallel? Here’re some real-world use cases:

  • A music streaming service may need to iterate through 2 arrays in parallel, one containing the song titles and the other containing the artist names, in order to display them together in a playlist.
  • A game developer may need to iterate through 2 arrays in parallel, one containing the x-coordinates and the other containing the y-coordinates of game objects, in order to update their positions in the game world.

Done!