簡體   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);

我是使用 reduce function 的新手,它有點復雜。

我正在嘗試展平嵌套數組,但我真的不知道下一步該做什么。

您已經提到了解決方案,您只需要實現它 - reduce concat中的累加器:

 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);

但是,如果您想在 map 內部做一些事情,這才是真正有利的,如下所示:

 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM