【问题标题】:How can I reduce or flatten an array of arrays using the Array.concat() method inside the callback function for Array.reduce()如何在 Array.reduce() 的回调函数中使用 Array.concat() 方法减少或展平数组数组
【发布时间】:2020-09-06 01:07:24
【问题描述】:

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

我正在尝试展平嵌套数组,但我真的不知道下一步该做什么。

【问题讨论】:

  • 这能回答你的问题吗? Merge/flatten an array of arrays
  • 欢迎来到 SO。请记住,在提出新问题之前尝试在 SO 中搜索已有的答案。如果已经存在的答案没有(完全)回答您的问题,那么最好开始一个新问题,引用现有问题并进一步详细说明未回答的问题。也可以看看How do I ask a good question?
  • 您已经从@CertainPerformance 得到答案,如果它回答了您的问题,请记得接受。
  • 其实,this回答已经提到的问题Merge/flatten an array of arrays完全回答了你的问题。

标签: javascript arrays concatenation reduce


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 2022-07-18
      • 1970-01-01
      • 2019-12-07
      • 2017-02-10
      • 2019-12-21
      • 2022-10-02
      • 2020-02-11
      • 2017-12-26
      相关资源
      最近更新 更多