I am facing a challenge with an array called projects
. Within each project
, there exists another array of employees
. Each employee is identified by a unique id
. My goal is to consolidate all employees
from all the projects
into one array while eliminating any duplicates.
To achieve this, I have considered utilizing a Map<number, Employee>
structure where the key corresponds to the employee's id. This allows me to check if an employee already exists in the map based on their id before adding them:
this.projects.forEach(project => {
project.employees.forEach(employee=> {
if (!this.employeeIdToEmployeeMap.has(employee.id)) {
this.employeeIdToEmployeeMap.set(employee.id, employee);
}
})
});
Next, I can extract the values from the map and convert them into an array:
this.employees = Array.from(this.employeeIdToEmployeeMap.values());
Now, I successfully have a consolidated list of employees
across all projects
without any redundancies.
Are there alternative methods to enhance this process? Can it be optimized to run in O(n) time complexity?