【发布时间】:2021-06-11 10:42:09
【问题描述】:
我正在尝试让这段代码运行得更实用。
我想根据list 中的名称选择过滤一组数据,然后根据每个人的ReportsTo 递归查找他们的直线经理,但前提是Rank 大于3 .
这可行,但有没有更好更简洁的方法来实现相同的结果?
const data = [
{
Name: 'Peter',
ReportsTo: '',
Rank: 1
},
{
Name: 'Tom',
ReportsTo: 'Peter',
Rank: 2
},
{
Name: 'Maria',
ReportsTo: 'Tom',
Rank: 3
},
{
Name: 'Liam',
ReportsTo: 'Maria',
Rank: 4
},
{
Name: 'John',
ReportsTo: 'Peter',
Rank: 3
},
{
Name: 'Fiona',
ReportsTo: 'Liam',
Rank: 5
}
]
// Start with only these names
const list = ['Fiona', 'Tom']
const filtered = data.filter(({Name}) => list.includes(Name))
// Recursively find the missing managers of the list names if the rank is not below 3
const findManager = (manager) => {
const next = data.find(({ Name}) => Name === manager)
return next.Rank > 3
? [next, ...findManager(next.ReportsTo)]
: [next]
}
// Check the line managers for the filtered array and store them
const missingManagers = []
for (const { ReportsTo, Rank} of filtered) {
if(!list.includes(ReportsTo) && Rank > 3) {
missingManagers.push(...findManager(ReportsTo))
}
}
// Merge the missing managers with the filtered list
const result = [...missingManagers, ...filtered]
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
【问题讨论】:
标签: javascript arrays object ecmascript-6 ecmascript-2016