Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property.

let arrayA = [{id: 1, modifiedOn: 1234}, {id: 2, modifiedOn: 1234}, {id: 3, modifiedOn: 1234}]

let arrayB = [{id: 4, modifiedOn: 1234}, **{id: 2, modifiedOn: 1235}**, {id: 5, modifiedOn: 1234}]

let arrayC = [{id: 6, modifiedOn: 1234}, {id: 7, modifiedOn: 1234},
**{id: 5, modifiedOn: 1235}**

let arrayD = [**{id: 1, modifiedOn: 1235}**, {id: 8, modifiedOn: 1234}, {id: 9, modifiedOn: 1234}]

Upon examining the arrays above, it is clear that ids 2, 5, and 1 are present in more than one array. The rule is to keep the item with the highest value for the modifiedOn property and remove the others.

Answer №1

https://codepen.io/vitkarpov/pen/GRpZzqx

function creatingSearchIndex(arrays) {
  const index = {};

  for (let i = 0; i < arrays.length; i++) {
    for (let j = 0; j < arrays[i].length; j++) {
      const {id, modifiedOn} = arrays[i][j];
      index[id] = index[id] || {};
      index[id][modifiedOn] = [arrays[i], j];
    }
  }
  return index;
}

function removingDuplicates(...arrays) {
  const searchIndex = creatingSearchIndex(arrays);

  Object.keys(searchIndex).forEach((id) => {
    const index = searchIndex[id];
    const modifiedOnRecords = Object.keys(index);

    // skip first, it corresponds to the value with the smallest modifiedOn value
    for (let i = 1; i < modifiedOnRecords.length; i++) {
      const modifiedOn = modifiedOnRecords[i];
      const [arr, j] = index[modifiedOn];
      arr.splice(j, 1);
    }
  });
}

let arrayX = [{id: 1, modifiedOn: 1234}, {id: 2, modifiedOn: 1234}, {id: 3, modifiedOn: 1234}]
let arrayY = [{id: 4, modifiedOn: 1234}, {id: 2, modifiedOn: 1235}, {id: 5, modifiedOn: 1234}]
let arrayZ = [{id: 6, modifiedOn: 1234}, {id: 7, modifiedOn: 1234}, {id: 5, modifiedOn: 1235}]
let arrayW = [{id: 1, modifiedOn: 1235}, {id: 8, modifiedOn: 1234}, {id: 9, modifiedOn: 1234}]

removingDuplicates(arrayX, arrayY, arrayZ, arrayW);

This problem is quite interesting and would make a great whiteboard interview question!

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

Having trouble centering an icon in a cell within AG Grid?

I am struggling with aligning my checkmarks within the cells of my AG Grid. Currently, they are all left aligned but I need them to be centered. Adjusting the alignment for text is not an issue, but I can't seem to center the material icons. It appear ...

Having trouble making changes to MUI TextFields once they've been filled in with data from an

My goal is to make MUI TextFields editable even after they have been filled with data from an API. The TextFields are getting populated successfully. I attempted using an onChange function, but it only allowed one additional character to be entered befor ...

Trouble with jQuery delay in updating the CSS attribute while using fadeIn

After writing a simple JQuery code, I noticed that every time I click on 'eat', the animation lags. Is there any way to preload this animation for smoother performance? The #custom_menu element is a full-page section with a fixed position (simil ...

Discover the steps to implement a live user list in a chat application with the help of angular.js, socket.io, and node

Currently, I am in the process of developing a chat application with AngularJS and Socket.io. The current status of my project allows users to send and receive messages from different individuals. To gain access to the chatbox, users need to input their na ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

Setting a menu item as active in a SvelteKit app: A step-by-step guide

I encountered an issue with the main navigation menu in my sveltekit application. The problem is that when the app is loaded or refreshed, the active menu item corresponding to the current URL is not set. After struggling to find a solution online, I manag ...

What is the method to insert a new <input> element after the last input field has been filled in

I recently started working on a form using StackBlitz, but I've hit a roadblock and need some guidance on how to proceed. My goal is to achieve a similar effect like the one shown in this gif: https://i.stack.imgur.com/76nsY.gif and I'd like to ...

Trouble accessing files in the assets folder of Angular 2

I am encountering a 404 error when attempting to access a local file within my application. I am unable to display a PDF that is located in a sub-folder (pdf) within the assets folder. I am using CLI. <embed width="100%" height="100%" src="./assets/pdf ...

Encountered an issue during the migration process from AngularJS to Angular: This particular constructor is not compatible with Angular's Dependency

For days, I've been struggling to figure out why my browser console is showing this error. Here's the full stack trace: Unhandled Promise rejection: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependen ...

Tips on retaining the value of $index in ng-repeat and storing it within the array

I currently have a cart for shopping. The code for the "add to cart" function looks something like this (shortened): "add" : function(code) { codes.push({ "id" : code.id, "order" : "N/A", ...

What is the best way to transfer an argument from a parsed JSON value to an onclick function?

In our dataset, we have a specific table that contains valuable information. My main objective is to transfer an argument extracted from parsed JSON data to a separate JavaScript function known as newStory(value['stories']) using the onclick meth ...

The AngularJS templates' use of the ternary operator

Is there a way to implement a ternary operation in AngularJS templates? I am looking for a way to apply conditionals directly in HTML attributes such as classes and styles, without having to create a separate function in the controller. Any suggestions wo ...

Creating a user-friendly form with validation in a Vue application using Vuetify.js

I am in the process of incorporating a contact form with basic validation on a Vue.js website using an example from Vuetify.js. Being new to this, I'm unsure about how to implement it within a Vue component. My goal is to have simple client-side form ...

Attempting to have the command "npm run dev" generate two separate shell instances

For my nuxt project, I decided to use json-server as the local server. My goal is to automate the process of launching the server and running the project on a separate shell instance by using the command "npm run dev". After some exploration, this is the ...

Is it possible to integrate ngx-translate with database-supported translations?

I am managing a vast database (pouchDB) that stores translations, with each language having its own dedicated database. How can I leverage ngx-translate to easily access these translations directly from the database? ...

Displaying Previously Selected Value in HTML Dropdown Menu

Using a combination of PHP and HTML, I have created an HTML table that is generated using a PHP while loop. The dropdown menu on the page displays all distinct portfolio names from my MySQL database by executing the following code: $query2 = "SELECT DISTI ...

Integrating data between Java and JavaScript within the Wikitude platform is essential for leveraging AR.RelativeLocation

After passing an integer from Java to JavaScript, I am attempting to use the value to adjust the altitude of an object. I included the variable in RelativeLocation var location = new AR.RelativeLocation(null, 8, 0, a); The issue arises when it disregards ...

Issue with Date generation in TypeScript class causing incorrect date output

I have a simple code snippet where I am creating a new Date object: var currentDate = new Date(); After running this code, the output value is: Sat May 11 2019 13:52:10 GMT-0400 (Eastern Daylight Time) {} ...

What is the best way to display two arrays next to each other in an Angular template?

bolded text I am struggling to display two arrays side by side in an angular template. I attempted to use ngFor inside a div and span but the result was not as expected. A=[1,2,3,4] B=[A,B,C,D] Current Outcome using ngFor with div and span : Using Div : ...

Properly aligning text with checkboxes using HTML/CSS and tags like <span> or <div>

My goal is to have the text displayed as a block in alignment with the checkbox, adjusting based on the sidebar's width. For reference: Current Layout Preferred Layout I have shared the code on CodePen (taking into account screen resolution and wi ...