30秒学会 JavaScript 片段 · 2017年7月13日

30秒学会 JavaScript 片段 – unzip

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 =>
  arr.reduce(
    (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
    Array.from({
      length: Math.max(...arr.map(x => x.length))
    }).map(x => [])
  );

使用样例

unzip([['a', 1, true], ['b', 2, false]]); // [['a', 'b'], [1, 2], [true, false]]
unzip([['a', 1, true], ['b', 2]]); // [['a', 'b'], [1, 2], [true]]