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

Utilize Angular for the front-end user interface and Asp.Net for the backend within the same Azure App

I am facing a challenge with deploying Angular and Asp.Net together on the same app service in Azure. Despite defining the Physical Path for the Angular project, it is not visible on the website and instead shows an error. Interestingly, when I deploy only ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...

incorrect choice of ngClass

Having sifted through numerous queries, I have come to this realization... The angular [ngClass] is behaving oddly when it comes to values like 10, 24, and 100. I can't seem to figure out the reason behind this behavior. Perhaps someone here might be ...

Access array information using AngularJS

Sorry for any language issues. I am trying to figure out how to extract an array data from AngularJS in order to save it using Node.js. This is my AngularJS script: angular.module('myAddList', []) .controller('myAddListController&apos ...

Ember Component Incorporating Keyboard Input

I recently developed an ember component that features a rectangular block in a green canvas. Everything is working smoothly so far. However, I am facing some challenges with implementing keyboard input commands (A S D W) to navigate the rectangle within t ...

Turning off @Output as Observable: A step-by-step guide

I have a query regarding unsubscribing Outputs in Angular. While I am aware that EventEmitter is automatically cleaned up, there was a time when I needed to use an Observable as my Output. Specifically, I wanted to take an Output that emitted events at mos ...

The issue arises when attempting to utilize ExpressJS middleware in conjunction with NextJS Link feature

Incorporating Next with Express routes, I have set up a scenario where /a should only be accessible to authorized individuals, while /b is open to the public. ... other imports... const app = next({ isDev }) const handle = app.getRequestHandler() async f ...

How can I retrieve properties from a superclass in Typescript/Phaser?

Within my parent class, I have inherited from Phaser.GameObjects.Container. This parent class contains a property called InformationPanel which is of a custom class. The container also has multiple children of type Container. I am attempting to access the ...

Dealing with substantial ajax responses using JavaScript

Currently, I am in the process of developing a website that utilizes jQuery File Tree. However, there is an issue with the enormous size of the AJAX response from the server - 900 KB and containing approximately 70,000 'files' (which are not actu ...

Ways to fix the perpetual cycle in adal-angular4 following authentication redirect

I have been working on an Angular 8 application that utilizes Microsoft Azure Active Directory authentication with adal-angular4. I've successfully set up an ASP.NET Core API linked to a client app on Azure. To configure Active Directory, I referred ...

Having trouble viewing the initial value in an AngularJS2 inputText field

I'm having trouble displaying the initial value in inputText. I'm unsure of what mistake I'm making, but the value should be showing up as expected. Kind regards, Alper <input type="text" value="1" [(ngModel)]="Input.VSAT_input1" name= ...

Exploring an alternative perspective on successful login in angular.js

Today was the beginning of my project to convert a website to angular.js. The main page is served by index.html and includes ng-view for other views such as login and signup. Working closely with a backend developer, I have successfully integrated a rest c ...

What is the best way to avoid having multiple files in a JavaScript file input when a user selects a new file?

I am trying to implement a file input using vanilla JavaScript, and my goal is to restrict the user to uploading only a single file at a time. The issue I am facing is that if the user repeatedly selects a file and clicks the upload button, the file gets ...

What methods can I use to evaluate the efficiency of my website?

Is there a way to assess and improve website performance in terms of load time, render time, and overall efficiency? I've heard of YSLOW for firebug, but am curious if there are any other tools or websites available for this purpose. ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

Oops! An issue occurred: The value 'NgxMatDrpModule' was not expected in the specified file path: node_modules/ngx-mat-daterange-picker/ngx-mat-daterange-picker.d.ts

Encountered an error while building an Angular 7 app using the command ng build --configuration=dev. The exception shows a single quote prefixed to NgxMatDrpModule. Even after deleting node_modules, package-lock.json and reinstalling node modules, the issu ...

Running end-to-end test in Angular application based on specified configuration

Currently, I am immersed in a project centered around Angular7 where e2e tests are crafted using protractor. I have recently implemented a new feature in the project that I aim to control through a functional switch. When the switch is turned ON, the feat ...

"Encountered a floating-point issue when trying to read an Excel file with

When a user uploads an Excel file that contains decimal, string, and Unicode characters, I am encountering an issue with floating point errors when reading certain decimal values. For instance, a number like 0.15 is being read as 0.150000000002 in some c ...

Harness the power of electrons with the simple push of a button - initiating program execution

Recently, I delved into Electron with the desire to create a small application for myself. This app would allow me to run different programs or games by simply clicking on a link. My goal is to have the program/game start automatically when I open the Ele ...

Changing the output of a service by using spyOn: A step-by-step guide

There is a specific service available: export class CounterService { random: any = { value: 123, date: 456, }; getRandom() { return this.random; } } A certain component utilizes this service. Within this component, the variable &apos ...