Array Zip Function in JavaScript

Level 4254 keystrokes

A zip function combines two arrays element-by-element into an array of pairs.

JavaScript code

// Define a zip function using map
// For each element in arr1, create a pair with corresponding arr2 element
1const zip = (arr1, arr2) => arr1.map((val, i) => [val, arr2[i]]);
// Create two parallel arrays
2const names = ["Alice", "Bob", "Charlie"];
3const ages = [25, 30, 35];
// Zip them together
4const zipped = zip(names, ages);
// Print the zipped array of pairs
5console.log(zipped);
// Iterate with destructuring to print each pair
6zipped.forEach(([name, age]) => console.log(`${name}: ${age}`));

Output

[ [ 'Alice', 25 ], [ 'Bob', 30 ], [ 'Charlie', 35 ] ]
Alice: 25
Bob: 30
Charlie: 35
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • ,× 9
  • (× 8
  • )× 8
  • =× 7
  • ;× 6
  • "× 6
  • [× 5
  • ]× 5
  • .× 4
  • >× 3

More JavaScript examples at level 4

← JavaScript typing practice