javascript - 如何在 Array.reduce() 的回调函数中使用 Array.concat() 方法减少或展平数组数组
问题描述
//Bonus - uncomment lines 15 and 17
const arrays = [["how", "now"], ["brown", "cow"]];
const flattenedArray = arrays.reduce((a,c) => a + c);
// The below line should console.log: ["how", "now", "brown", "cow"]
console.log(flattenedArray);
我是使用 reduce 函数的新手,它有点复杂。
我正在尝试展平嵌套数组,但我真的不知道下一步该做什么。
解决方案
您已经提到了解决方案,您只需要实现它 -回调concat
中累加器的当前项目:reduce
const arrays = [["how", "now"], ["brown", "cow"]];
const flattenedArray = arrays.reduce((a,c) => a.concat(c));
console.log(flattenedArray);
但.flat()
会容易得多:
const arrays = [["how", "now"], ["brown", "cow"]];
const flattenedArray = arrays.flat();
console.log(flattenedArray);
推荐阅读
- javascript - 将数据值更改为相同值时vue watch不触发
- docker - 我可以独立扩展所有主管流程吗?
- google-sheets - 交易日志中的连续分组加权平均值和总和
- amazon-cloudfront - 无法使用 AWS CloudFront 签名 Cookie 播放 HLS m3u8 文件
- swift - 添加详细信息后如何使标签显示
- javascript - 如何在 React JS 中切换到另一个组件之前保存状态
- node.js - 按所选类别获取 Firestore 函数
- vba - 宏 for 循环遍历 Outlook 未读电子邮件
- python - 将字符列表加入单词列表
- java - Keycloak 密码黑名单不适用于特殊符号