Sling Academy
Home/JavaScript/JavaScript: How to iterate through 2 arrays in parallel

JavaScript: How to iterate through 2 arrays in parallel

Last updated: March 08, 2023

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!

Next Article: JavaScript: Checking if an array contains a given object

Previous Article: JavaScript: 2 Ways to Get a Random Element from an Array

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration