简体   繁体   English

如何在 Array.reduce() 的回调 function 中使用 Array.concat() 方法减少或展平 arrays 的数组

[英]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);

I'm new to using the reduce function and it's a little bit complicated.我是使用 reduce function 的新手,它有点复杂。

I'm trying to flatten the nested array but I don't really know what to do next.我正在尝试展平嵌套数组,但我真的不知道下一步该做什么。

You mentioned the solution already, you just need to implement it - concat the current item to the accumulator inside the reduce callback:您已经提到了解决方案,您只需要实现它 - reduce concat中的累加器:

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

But .flat() would be much easier:但是.flat()会容易得多:

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

Another option - flatMap:另一种选择 - flatMap:

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

But it is only really advantageous if you want to do something inside the map, like this:但是,如果您想在 map 内部做一些事情,这才是真正有利的,如下所示:

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

Or like this:或者像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM