【问题标题】:How do I use reduce function instead of recurring function?如何使用 reduce 函数而不是循环函数?
【发布时间】:2021-04-20 19:21:31
【问题描述】:

是否可以使用 reduce 代替这种递归? 基本上,如果有分组/嵌套的行,我只想获得最年轻的(非常行,或者如果我用树来解释,则为叶子)行。

数据:

行:[

0: {group: true, children: [youngest1, youngest2, youngest3]}

1: {group: false, //youngest4 行数据...}

]

此代码收集 [rows[0].children[0], rows[0].children[1], rows[0].children[2], rows[1]]

function getChildRows(rows, importRows) {
  rows.forEach(row => {
    if (row.group) {
      importRows = getChildRows(row.children, importRows);
    } else {
      importRows.push(row);
    }
  });
  return importRows;
}

这是我的尝试

function getChildRows(rows, importRows) {
  return rows.reduce((accumulator, row) => {
    if (row.group) {
      importRows= getChildRows(row.children, accumulator);
    } else {
      accumulator.push(row);
    }
    return accumulator;
  }, []);

但我没有得到想要的结果

【问题讨论】:

  • 您可能想要添加示例输入数据和您期望的结果。另外,“我只想得到最年轻的”,除非我弄错了,否则您当前的代码不会这样做? 编辑哦,我明白了。我猜只有最深的。除非他们没有孩子,否则不是父母?
  • 不清楚为什么要使用reduce,但必须将importRows设置为reduce
  • @blex 使用示例数据更新 - 代码只收集最年轻的

标签: javascript recursion reduce


【解决方案1】:

您可以简单地使用flatMap()

function getChildRows(rows) {
   return rows.flatMap(row => row.group ? getChildRows(row.children) : row)
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap#alternative

【讨论】:

    【解决方案2】:

    你可以这样做:

    const rows = [
      {
        group: true,
        name: 'row[0]',
        children: [{name: 'children[0]'}, {name: 'children[1]'}, {name: 'children[2]'}]
      },
      {
        name: 'row[1]'
      }
    ];
    
    function getChildRows(rows) {
      return rows.reduce((acc, row) => {
        return acc.concat( row.group ? getChildRows(row.children) : [row] );
      }, []);
    }
    
    console.log( getChildRows(rows) );

    【讨论】:

    • arr.reduce((acc, x) => acc.concat(f(x)), []) 有一个名字,arr.flatMap(f)
    猜你喜欢
    • 2016-01-19
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    相关资源
    最近更新 更多