
创建一个数组数组,将zip生成的数组中的元素取消分组。
使用Math.max(),Function.prototype.apply()获取数组中最长的子数组,应用Array.prototype.map()方法使每个元素成为一个数组。
使用Array.prototype.reduce()和Array.prototype.forEach()将分组值映射到单个数组。
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]]
更多内容请访问我的网站:https://www.icoderoad.com