Mastering the art of efficiently executing a double for loop

Currently, there is a direct one-to-one relationship between user and employee. In order to retrieve the data separately, I need to determine the most effective method for assigning each employee to their corresponding user. At the moment, I am using two nested forEach loops (although I have discovered that this method is 96% slower than using a simple for loop).

I am actively seeking a more optimized approach to handle this scenario. The variable ids contains a list of user IDs. The goal is to match these IDs and assign the appropriate employee to the corresponding user.

this.employeeService.query({'userId.in': ids}).subscribe(employeeData => {
    employeeData.body.forEach(employee => {
        this.users.forEach(user => {
            if (user.id === employee.userId) {
                user.employee = employee;
            }
        });
    });
});

Are there alternative methods you could suggest that may prove more efficient in achieving this task?

Answer №1

If you want to streamline your search process, consider utilizing a HashMap-like structure. In the realm of JavaScript, a basic object can serve this purpose well. Establish a UserMap that links user ids to their respective employees.

let UserMap= {}
employees.forEach( employee =>UserMap[employee.userId]= employee)

From there:

users.forEach( user=> user.employee = UserMap[user.id])

By transforming the nested loop into two separate for-loops, efficiency is greatly enhanced.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error Encountered with Angular MatTableDataSource

I encountered the following error : [ts] Argument of type 'Company' is not assignable to parameter of type 'Company[]'. Property 'includes' is missing in type 'Company'. How can I insert an Array Object into ...

Transforming various date formats into the en-US format of mm/dd/yyyy hh:mm:ss can be accomplished through JavaScript

When encountering a date format in en-GB or European style (mm.dd.yyyy), it should be converted to the en-US format (mm/dd/yyyy). If the date is not already in en-US format, then it needs to be converted accordingly. ...

HTML: Mark the chosen hyperlink or tag

In my HTML page, I am looking to keep the link selected when it is clicked on. Here is the initial HTML code: <table class="main-dev"> <tr> <td> <a class='titleForm' style="cursor:pointer"> ...

Is it feasible to retrieve ADFS server users through the Auth0 API in an Asp.net C# MVC application?

Currently, I have successfully integrated ADFS user authentication using the Auth0 API in an ASP.Net application. However, I now have a new requirement to retrieve all ADFS users utilizing the Auth0 API. Is it feasible to fetch all ADFS users through the ...

What is the best way to determine the size of a $resource object?

After receiving a variable from the API, I printed it out like this: console.log(arr) Resource {0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, 5: {…}, 6: {…}, 7: {…}, 8: {…}, 9: {…}} However, when attempting to determine the length of the ...

Asynchronous problem when using Firebase calls within an Angular ForEach loop

Here's the code snippet I'm working with: getTotalBookListCost(bookList:string[]):number { let cost=0; bookList.forEach(el=>{ this.store.doc("Books/"+el).get().subscribe(data=>{ let temp=<Book>data.da ...

Exploring Scroll Functionality for Inner Components Within Mat-tab

I am currently working on a small attendance project that involves using table components within mat-tab elements. However, I am facing an issue where the overflow from the table causes the entire component to scroll, when in fact I only want the table its ...

Troubleshooting: Custom HTML Attribute in Angular 8 Component HTML Not Functioning as Expected

I have a unique situation in my Angular 8 application where I utilize custom HTML attributes and then use jQuery to fetch those attributes for various styling purposes such as setting background images and adjusting the height of div elements. Below is th ...

Improve the efficiency of variance computation as the current for loop implementation is not optimal

Continuing from the question addressed in this other resource [Addressing Slow Performance of Apply Function in R I am faced with the task of calculating a specific formula for numerous species, requiring the results obtained from the referenced link abov ...

Experience the power of Mapbox's expressive features through dynamic text sizing with Get Expression!

I am in need of help to add a single layer for text symbols that are sourced from a FeatureCollection. Each feature has multiple text sizes and styles stored in their properties. I have been utilizing Mapbox's data-driven expressions to assign these s ...

Is it possible for me to learn angular2 using the examples provided on the official website?

Looking to dive into Angular2, but struggling to find comprehensive documentation? I decided to start my journey by studying Angular2 on its official website: https://angular.io/docs/ts/latest/tutorial/ Additionally, I downloaded an Angular2 boilerplate f ...

Guide to setting a default value in a asynchronous list within an ng-select (Angular 2+, ng-select, and rxjs)

I recently started using ng-select and incorporated the typeahead feature to fetch server data as the user types. This is how I implemented it: I created an observable for the list of agents which gets updated whenever a new string is inserted agents$: Ob ...

The importance of displaying doughnut chart tooltips in Angular 5 console

Is there a way to consistently display tooltips for a doughnut chart? This code snippet might help: Chart.pluginService.register({ beforeRender: function(chart) { if (chart.config.options.showAllTooltips) { // create an array of tooltips // we ...

The variable 'module' is required to be of type 'any', but it is currently identified as type 'NodeModule'

I am currently working on a project using Angular and have just installed version 1.0.5 of ng2-dropdown-treeview. After installation, I restarted my server by running npm start. Upon checking the server log, I encountered the following error message: [PA ...

JavaScript library experiencing import issues with Typescript custom type

Working on a Vue project with TypeScript, I encountered an issue when importing a custom type created for the vue-numeral-filter package. The error message received is as follows: ERROR in /Users/bmartins/Development/app-invest/src/main.ts(14,30): 14:30 ...

Tips for creating a Bitbucket pipeline to deploy an Angular Universal application

I'm currently working on deploying my Angular universal app on a server using Bitbucket pipelines. The scripts I've written in bitbucket-pipelines.yml are as follows: pipelines: default: - step: name: Build app caches: ...

Tips for debugging Typescript code in Visual Studio Code using ts-node-dev and ensuring accurate line numbering

Launching my Typescript project involves using the following command: ts-node-dev --preserve-symlinks --inspect=0.0.0.0 -- src/server.ts While I am able to debug it using Visual Studio Code, the debugger tends to break at incorrect lines. My assumption ...

What is the best way to retrieve a {collection object} from a JavaScript map?

My application utilizes a third-party library that returns the map in the following format: public sids: Map<SocketId, Set<Room>> = new Map(); When I try to access it using the code below: io.of("/").adapter.sids.forEach(function(va ...

The attribute 'X' is not present in the specified type 'IntrinsicAttributes & InferPropsInner'

I've been restructuring my code from a .js file to a .tsx file, as seen below: import React, { useEffect, useState } from 'react' import PropTypes from 'prop-types' import { checkMobile } from '../../utils/common' import ...

Validation in custom components within an Angular reactive form is failing to function correctly

Currently, I am in the process of developing a new component within Angular reactive forms. To view my sample project: https://stackblitz.com/edit/angular-pyi9jn The angular form I created follows this structure: form - simple counter The form output i ...