On this script I look up properties in an array of objects. There is an original array of strings list
to get the objects that match the name
property, then I look up their respective line managers, reports
recursively but only up to the rank
2, finally I merge their entries with the manager ones.
I was wondering if there is a more efficient way to achieve this result as I am having to make an object to index the managers that have already been checked, otherwise I get duplicates when two people have the same manager. Also having to specify the rank
limit twice.
const data = [
{
name: 'rebecca',
reports: '',
rank: 1
},
{
name: 'will',
reports: 'rebecca',
rank: 2
},
{
name: 'jose',
reports: 'will',
rank: 3
},
{
name: 'tomas',
reports: 'jose',
rank: 4,
},
{
name: 'matt',
reports: 'jose',
rank: 5
},{
name: 'alison',
reports: 'john',
rank: 5
}
]
// Initial list of names
const list = ['tomas', 'matt']
// Get the people on the list first
const filterList = data.filter(({ name }) => list.includes(name))
// Helper object to account for managers already checked and avoid duplicates
const managers = {}
// Find missing managers recursively
const findManager = (manager) => {
const next = data.find(({ name }) => name === manager)
managers[next.name] = true
return next.rank > 2 ? [next, ...findManager(next.reports)] : [next]
}
// Get the line managers for the filterList array
const missingManagers = []
for (const { reports, rank } of filterList) {
if (!list.includes(reports) && rank > 2 && !managers[reports] ) {
missingManagers.push(...findManager(reports))
}
}
const result = [...missingManagers, ...filterList]
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
tomas
tomatt
, or the management chain from each of these persons as thereports
person? How isrank
related to the given (person) object? Is rank is where that person falls with a given management chain, say, starting withtomas
and ending withmatt
? I'm just seeing this as a sorting issue so far. \$\endgroup\$