如何使用 reduce 函数而不是 recurring 函数?
How do I use reduce function instead of recurring function?
是否可以使用 reduce 代替递归?
基本上,如果有 grouped/nested 行,我只想获取最年轻的行(如果我用树来解释的话,就是最年轻的行,或者叶子)行。
数据:
行数:[
0: {group: true, children: [youngest1, youngest2, youngest3]}
1: {group: false, //最年轻的4行数据...}
]
此代码收集[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;
}, []);
但是我没有得到想要的结果
您可以简单地使用 flatMap()
function getChildRows(rows) {
return rows.flatMap(row => row.group ? getChildRows(row.children) : row)
}
你可以这样做:
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) );
是否可以使用 reduce 代替递归? 基本上,如果有 grouped/nested 行,我只想获取最年轻的行(如果我用树来解释的话,就是最年轻的行,或者叶子)行。
数据:
行数:[
0: {group: true, children: [youngest1, youngest2, youngest3]}
1: {group: false, //最年轻的4行数据...}
]
此代码收集[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;
}, []);
但是我没有得到想要的结果
您可以简单地使用 flatMap()
function getChildRows(rows) {
return rows.flatMap(row => row.group ? getChildRows(row.children) : row)
}
你可以这样做:
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) );