Create a distinct list based on the objects' identifiers with optimal efficiency

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?

Answer №1

If you want to accomplish this, you can utilize the reduce method in the following way:

const teams: { players: { id: any }[] }[] = [
    { players: [{ id: 12 }, { id: 17 }] },
    { players: [{ id: 15 }, { id: 17 }] }
];

const playerMap = teams.reduce((players, team) => ({
    ...players,
    ...team.players.reduce((playersList, player) => ({
        ...playersList,
        ...(playersList[player.id] ? {} : { [player.id]: player })
    }), players as any)
}), {} as any)

console.log(Object.values(playerMap)); // Outputs: [ {id: 12}, {id: 15}, {id: 17} ]

Answer №2

Here is a simple O(nlogn) solution:

  1. Place all the employees into a list
  2. Sort the list
  3. Add employees to a new list while skipping consecutive duplicates

What complexity does your solution have? Well, converting the map to a list should be O(n) given any reasonable implementation of the map. The outer loop executes n times. So, the question is, what is the complexity when adding an element to a map? Worst-case time is clearly linear (assuming a list-based bucket and open hashing; could be log(n) if using a tree or something instead), best-case time is constant. Since our problem involves putting n items into a map, we need to consider the amortized complexity. With a resizable backing store and multiplicative expansion when running out of space, it's possible to achieve O(1) amortized complexity for the add operation. If that's how your map operates, then you have O(1) assuming a good hash function.

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

Exploring the potential of AssemblyScript in creating immersive WebXR

I have been exploring three.js and webXR for some time now, and I wanted to incorporate it into assembly script. While I know how to make webXR work in TypeScript, I encounter an error when trying to use it in assembly script with the import statement. Her ...

Leveraging Angular 2 directives in TypeScript to bind a value from a custom control to an HTML control

I have created a unique custom directive named "my-text-box", and within this directive, I am utilizing the HTML control <input>. I want to pass values from my custom control to the HTML input control. In Angular 1, I would simply do something like & ...

The selector in Angular ngrx 8 is failing to retrieve a value

I have experience with Angular but I am new to ngrx. I am attempting to retrieve values from my server and display them on the screen. I can see that the values are coming back from the server, and then the effect is triggered by the action: https://i.ss ...

Postpone the initial click action triggered by the specified directive

Is it possible to create a directive that prompts for confirmation when a button is clicked? This would involve storing the original event and only executing it once the user confirms their choice. A similar behavior has been mocked here: https://stackbl ...

Eliminate a particular attribute from an array of objects

https://i.sstatic.net/O7lKv.pngHaving an issue with removing an item from an array object based on a specific property. Let me explain. delColumn($event: any, el: any) { if ($event.target && el > -1) { var colId: string = this.receivedData[ ...

What makes React Native unique when it comes to handling multiple data inputs?

Apologies for my limited English skills. I am trying to structure multiple data entries by adding separate JSON lines for each input, but currently it updates the previous data instead of creating a new one. Below is the sample code I am working with. var ...

Encountering an issue when attempting to import a non-source module from a node library while running a Typescript script

I have a script that takes input and utilizes the three.js library to apply geometric transformations to the data. I execute this script using ts-node pipeline.ts. Here is the structure of my project: ├── package-lock.json ├── package.json ├ ...

Steps for wrapping a class with a higher order component

Is it feasible to encapsulate a class component within a higher order component (HOC) that is also a class? import React, { Component } from "react"; import { View } from "react-native"; import { Toast } from "react-native-easy-toast"; const withToast = ...

Show blob file as a PDF document in a popup or dialog box using HTML and TypeScript

I am currently working on integrating TypeScript and HTML to showcase the result of a webservice call as a PDF in a popup/dialog within the same page. While I can successfully open the PDF in a new tab using the window.open(url) method, I'm encounter ...

We are in need of a provider for the Ionic Network native plugin

I have encountered an issue while trying to use Ionics native plugin "Network" as it fails due to a missing provider. To prevent any errors, I performed a fresh installation of Ionic along with the necessary dependencies: ionic cordova plugin add cordova- ...

the advantages of enforcing a type instance over using typeof in TypeScript

I am trying to export a type as an instance, rather than just a reference. I have experimented with various approaches, but so far the only solution I have found involves creating a static getter which I would prefer to avoid. Here is my context: I want t ...

The parameter type string does not match the argument type string | ArrayBuffer

Encountering a TS error in line 15 specifically with e.target.result. Error message: Argument type string | ArrayBuffer is not assignable to parameter type string  Type ArrayBuffer is not assignable to type string let fileTag = document.getElementById ...

Preventing duplicate namespace declarations in TypeScript

Let's say I have a variety of objects with the following data structure: { namespace: 'first'|'second'|'third' } Now, I need to include another object with the same data structure, but its namespace cannot be assigned ...

Tips for managing an array of observable items

In my current project, I am working with an Angular application that receives a collection from Firebase (Observable<any[]>). For each element in this collection, I need to create a new object by combining the original value with information from ano ...

Evaluating whether an imported function, which serves as a dependency of an adapter, is being invoked with accurate parameters within the adapter using the Jest testing framework

Here is how my test looks import { SlugGeneratorAdapter } from './slug-generator-adapter' import slugify from 'slugify' describe('SlugGenerator Adapter', () => { test('Should call the slug generator with the correct ...

Having trouble resolving the TypeScript error stating that "@types/express-serve-static-core/index has no exported member"? Here's how you

Encountering errors after upgrading node from version 14.18.0 to 20.16.0: ../node_modules/@types/express/index.d.ts node_modules/@types/express-serve-static-core/index"' has no exported member 'CookieOptions' node_modules/@types/express ...

Unable to display toast notification in React/MUI/Typescript project

Currently tackling error notifications targeted at 400,401, and 500 errors within a large-scale project. I am facing an issue where I want to integrate my ErrorToastNotification component into my layout.tsx file to avoid duplicating it across multiple page ...

What should you do when Node.js is unable to locate a module using the specified path?

Encountering the following error: Unable to import main.handler module. Error: Cannot find module '/function/code/skill/index' imported from /function/code/main.js. Stack: Nodejs 18, TypeScript 5.3.3. Interestingly, there is no error with import ...

Utilizing the useRef hook in React to retrieve elements for seamless page transitions with react-scroll

I've been working on creating a single-page website with a customized navbar using React instead of native JavaScript, similar to the example I found in this reference. My current setup includes a NavBar.tsx and App.tsx. The NavBar.tsx file consists o ...

Retrieve the object's value by utilizing the string index in TypeScript and proceed to access it further

interface IpPatientAddressDto { ... addressSeq: number; } interface IpPatientInfoDto { ... localAddress: IpPatientAddressDto; } const originalPatient:IpPatientInfoDto = { ... localAddress:{ addressSeq:0001 } } const createAddrCollec ...