Nathan Bell
Nathan Bell

Reputation: 167

How do I use reduce function instead of recurring function?

Is it possible to use reduce instead of this recursion? Basically if there are grouped/nested rows, I only want to get the youngest (the very rows, or leaf if I am explaining in terms of tree) rows.

data:

rows:[

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

1: {group: false, //youngest4 row data...}

]

This code collects [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;
}

This was my attempt

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

But i didn't get the desired result

Upvotes: 1

Views: 76

Answers (2)

ecoplaneteer
ecoplaneteer

Reputation: 1984

You can simply use 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

Upvotes: 2

blex
blex

Reputation: 25659

You could do it like this:

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

Upvotes: 0

Related Questions