简体   繁体   中英

Javascript Recursive Function doesn't work for arranging data

When I run this code, for some reason I believe the recursive arrange method is not doing the right thing. Any of the inner groupings are not present in the output for the filter function. What am I doing wrong with functional javascript?

 const def = x => typeof x !== 'undefined' const filter = ([x, ...xs], fn) => def(x) ? fn(x) ? [x, ...filter(xs, fn)] : [...filter(xs, fn)] : [] let arrange = t => { return { num: t.id, groups: t.groups.map(arrange) } } let data = [ {id: 1, groups: [{id: 3, groups: []}]}, {id: 4, groups: []}, {id: 5, groups: []} ] let groups = data.map(arrange) console.log(groups) // => [ { num: 1, groups: [ [Object] ] }, // { num: 4, groups: [] }, // { num: 5, groups: [] } ] let getById = g => { if (g.num === 3) { return true } else { return false } } let filtered = filter(groups, getById) console.log(filtered) // [] 

Before filtering you have to flatten the nested entries into a flat list:

 const flatten = groups => groups.flatMap(group => [group, ...flatten(group.groups)]);

That way you can easily do this:

 const result = filter(flatten(groups), byID);

to get an array of groups.


To maintain the tree order you'd have to recursively filter:

const advancedFilter = predicate => array => array.map(predicate).filter(it => it.take).map(it => it.value || it);

const use = (a, v) => v(a);

const filterGroups = predicate => advancedFilter(group => use(
  filterGroups(predicate)(group.groups), 
  filtered => ({ take: predicate(group) || !!filtered.length, value: { ...group, groups: filtered })
));

const result = filterGroups(byID)(groups);

Note that flatMap is very new, so you might not want to use it in production without a transpiler...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM