zip / unzipLoading saved progress…

zip / unzip

zip takes several arrays and groups their elements by position: the firsts together, the seconds together, and so on. unzip does the reverse, and zipObject pairs a keys array with a values array into an object. Together they line up parallel data — names with scores, columns into rows and back.

Implement all three. zip(...arrays) returns tuples grouped by index, padding shorter arrays to the longest length with undefined. unzip(pairs) inverts it. zipObject(keys, values) builds { keys[i]: values[i] }.

Signature

function zip(...arrays) {}          // group by index into tuples
function unzip(pairs) {}            // inverse of zip
function zipObject(keys, values) {} // { keys[i]: values[i] }

Examples

zip([1, 2], [3, 4]);            // [[1, 3], [2, 4]]
zip([1, 2, 3], ['a']);         // [[1, 'a'], [2, undefined], [3, undefined]]
unzip([[1, 3], [2, 4]]);       // [[1, 2], [3, 4]]
zipObject(['a', 'b'], [1, 2]); // { a: 1, b: 2 }

Notes

  • Group by index — the result's i-th tuple is [arrays[0][i], arrays[1][i], ...].
  • Pad to the longest — ragged lengths are filled with undefined, not truncated to the shortest.
  • unzip is zip inverted — regrouping tuples restores the original arrays.
  • zipObject lengths — extra keys get undefined values; extra values are ignored.
  • New structures, no mutation — return fresh arrays/objects; don't change the inputs.
Loading editor…