如何在Array.reduce()的回调函数中使用Array.concat()方法减少或压平一个数组?

问题描述 投票:-1回答:1

//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函数,有点复杂。

我想把嵌套的数组扁平化,但我真的不知道下一步该怎么做。

javascript arrays concatenation reduce
1个回答
2
投票

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

0
投票

另一个选择 - FlatMap:

const arrays = [["how", "now"], ["brown", "cow"]];
const flattenedArray = arrays.flatMap(a => a);
console.log(flattenedArray);

但只有当你想在地图里做一些事情时,它才是真正的优势,就像这样:

const arrays = [["how", "now"], ["brown", "cow"]];
const flattenedArray = arrays.flatMap(a => a.concat(a));
console.log(flattenedArray);

或者像这样:

const arrays = [["how", "now"], ["brown", "cow"]];
const flattenedArray = arrays.flatMap(a => a.map(b => b.toUpperCase()));
console.log(flattenedArray);
© www.soinside.com 2019 - 2024. All rights reserved.