简体   繁体   English

Javascript递归函数不适用于排列数据

[英]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. 当我运行这段代码时,出于某种原因,我认为递归的range方法没有做正确的事。 Any of the inner groupings are not present in the output for the filter function. 过滤器功能的输出中没有任何内部分组。 What am I doing wrong with functional javascript? 功能性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... 请注意flatMap是非常新的,因此您可能不希望在没有编译器的情况下在生产中使用它...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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