简体   繁体   中英

how to find managerchain for a given employeecode and how to find all employees under the given managercode

each employee (with given employeecode) works under a manager (respective managercode). and if any employee don't have managercode then he is the CEO. I want to write two functions getEmployeesOfManager and getManagerChainOfEmployee in javascript

var data=[
    {employeeCode: 20, managerCode: 30},
    {employeeCode: 30, managerCode: 40},
    {employeeCode: 40},
    {employeeCode: 50, managerCode: 40},
]
function getEmployeesOfManager(managerCode) {
    // write your code here
    // here we have to store all employees that comes under the manager of the given managercode in an array
}
function getManagerChainOfEmployee(employeeCode) {
    // write your code here
    // here we have to store all the managers which are above the given employeecode like for employeecode - 20 it will be [30,40] as 20 works under 30 and 30 works under 40.
}

Question 1 is simple
You just need to determine the managerCode of the data by ordinary traversal
Problem 2 is a little more complicated
First you need to find the employee with your current employeeCode
Determine if this employee exists
If it exists
then determine whether this employee is a normal employee
If it is
then iterate through the array and find the employee's supervisor
If the employee's supervisor exists
then record this supervisor
and then use this superior as the target
then recursively loop
Also, you can do a memorized search
Optimize performance by reducing unnecessary searches

var data=[
    {employeeCode: 20, managerCode: 30},
    {employeeCode: 30, managerCode: 40},
    {employeeCode: 40},
    {employeeCode: 50, managerCode: 40},
]
const visitedData = new Set()
function getEmployeesOfManager(managerCode) {
    let employees = []
    for (const item of data) {
        if (item.managerCode === managerCode) {
            employees.push(item)
        }
    }
    return employees
}
function getManagerChainOfEmployee(employeeCode) {
    const target = data.find(i => i.employeeCode === employeeCode)
        
    let chain = []
    if (target.managerCode) {
        chain = [target.managerCode]
        visitedData.add(`${target.employeeCode}-${target.managerCode}`)
        for (const item of data) {
            const id = `${item.employeeCode}-${item.managerCode}`
            if (item.employeeCode === target.managerCode && !visitedData.has(id)) {
                visitedData.add(id)
                chain.push(item.managerCode)
                chain = chain.concat(getManagerChainOfEmployee(item.managerCode))
            }
        }
    }

    return chain
}

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