//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);
另一个选择 - 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);