首页 > 解决方案 > 如何在 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 函数的新手,它有点复杂。

我正在尝试展平嵌套数组,但我真的不知道下一步该做什么。

标签: javascriptarraysconcatenationreduce

解决方案


您已经提到了解决方案,您只需要实现它 -回调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);


推荐阅读