碎片时间学编程「58]:取消组合数组元素

创建一个数组数组,将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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容