如何在 Array.reduce() 的回调函数中使用 Array.concat() 方法减少或展平数组数组
How can I reduce or flatten an array of arrays using the Array.concat() method inside the callback function for Array.reduce()
//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);
//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);