javascript
20 lines · 6 steps
Three ways to zip arrays in JavaScript
A small toolkit that pairs two arrays into tuples, an object, or a padded set of pairs.
Explained by
highlit
1function zip(keys, values) {
2 if (keys.length !== values.length) {
3 throw new RangeError('zip expects arrays of equal length');
4 }
5 return keys.map((key, index) => [key, values[index]]);
6}
7
8function zipToObject(keys, values) {
9 return Object.fromEntries(zip(keys, values));
10}
11
12function zipLongest(keys, values, fill = null) {
13 const length = Math.max(keys.length, values.length);
14 return Array.from({ length }, (_, index) => [
15 index < keys.length ? keys[index] : fill,
16 index < values.length ? values[index] : fill,
17 ]);
18}
19
20export { zip, zipToObject, zipLongest };
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Pairing arrays by index is just a map over one array reaching into the other.
- 2Object.fromEntries turns a list of key-value pairs directly into an object.
- 3Choosing to throw versus pad with a fill value is how you handle mismatched lengths.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/three-ways-to-zip-arrays-in-javascript-explained-javascript-3760/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.