Skip to content

Latest commit

 

History

History
42 lines (37 loc) · 1.17 KB

unzip.md

File metadata and controls

42 lines (37 loc) · 1.17 KB
title tags
unzip
array,intermediate

TS JS Deno

Creates an array of arrays, ungrouping the elements in an array produced by zip.

Use Math.max.apply() to get the longest subarray in the array, Array.prototype.map() to make each element an array. Use Array.prototype.reduce() and Array.prototype.forEach() to map grouped values to individual arrays.

const unzip = (arr: any[], size = 0) => {
  return arr.reduce(
    (acc, val) => (val.forEach((v: any, i: number) => acc[i].push(v)), acc),
    Array.from({
      length: size || Math.max(...arr.map((x) => x.length)),
    }).map(() => [])
  );
};
unzip([
  ["a", 1, true],
  ["b", 2, false],
]); // [['a', 'b'], [1, 2], [true, false]]
unzip([
  ["a", 1, true],
  ["b", 2],
]); // [['a', 'b'], [1, 2], [true]]
unzip(
  [
    ["a", 1, true],
    ["b", 2, false],
  ],
  3
); // [ ["a", "b"], [1, 2], [true, false], ]