简体   繁体   中英

How to avoid nested loop using TypeScript

I am working on application where I want to get the user names from employeeList array. Here is I am getting it by using nested loop but this not good practice. Here is my code

let _empList = await this.empService.getEmployeesList();
let taskEvents = await this.taskService.renderedTaskGridData(
  _tasksData,
  undefined
);

let associatesList = [];
for (let proj of this.projectsData) {
  let projTasks = [...taskEvents.filter((x) => x.ProjectId === proj.Id)];

  _empList.forEach((x) => {
    projTasks.forEach((y) => {
      y.AssociatedUsersId.forEach((z) => {
        if ((x.Id = z)) {
          associatesList.push(`${x.FirstName} ${x.LastName}`);
        }
      });
    });
  });
}

I need to get the list using best practice.

I'm going to go ahead and assume that the problem you are concerned with is the asymptotic complexity (ie - how much your runtime increases relative to the size of your input).

The way I'd solve that would be to make a time space trade-off, like so:

let associatesList = [];
const projectIds = new Set(this.projectsData.map((proj) => proj.Id));

const userIds = new Set(
  taskEvents
    .filter((task) => projectIds.has(task.ProjectId))
    .flatMap((event) => event.AssociatedUsersId)
);
const employees = _empList
  .filter((employee) => userIds.has(employee.Id))
  .map((employee) => `${employee.FirstName} ${employee.LastName}`);

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