Eliminate duplicate values in an array while preserving the original data in TypeScript

Two arrays are in my possession. The task at hand is to combine both arrays while ensuring that the resulting output contains all the records from arr1 and only unique records from arr2, with the "number" field being the key.

I am seeking advice on the best approach to achieve this desired outcome. In essence, I aim to merge the arrays and extract the unique "number" values, with the result encompassing all records from arr1 and solely distinct records from arr2.

let arr1 = [
  {
    "number": "1234",
    "Name": "test",    
    "data": [
      {
        "qty": 0,
        "val": 1.11
      },
      {
        "qty": 500,
        "val": 2.92
      },
      {
        "qty": 1000,
        "val": 2.84
      },
      {
        "qty": 1500,
        "val": 2.66
      }
    ]
  },
    {
    "number": "6776",
    "Name": "test9",    
    "data": [
      {
        "qty": 0,
        "val": 2
      },
      {
        "qty": 100,
        "val": 3
      },
      {
        "qty": 200,
        "val": 4
      },
      {
        "qty": 300,
        "val": 5
      }
    ]
  },
  
]

let arr2 = [
{
    "number": "1234",
    "Name": "test",    
    "data": [
      {
        "qty": 0,
        "val": 1.11
      }
    ]
  },
  {
    "number": "7896",
    "Name": "test4",    
    "data": [
      {
        "qty": 0,
        "val": 5.11
      },
      {
        "qty": 500,
        "val": 6.92
      },
      {
        "qty": 1000,
        "val": 3.84
      },
      {
        "qty": 1500,
        "val": 1.66
      }
    ]
  },
  {
    "number": "4567",
    "Name": "test2",    
    "data": [
      {
        "qty": 0,
        "val": 4.11
      },
      {
        "qty": 500,
        "val": 9.92
      },
      {
        "qty": 1000,
        "val": 5.84
      },
      {
        "qty": 1500,
        "val": 7.66
      }
    ]
  }
]


Upon merging the above two arrays, the expected output is as follows:

[
  {
    "number": "1234",
    "Name": "test",    
    "data": [
      {
        "qty": 0,
        "val": 1.11
      },
      {
        "qty": 500,
        "val": 2.92
      },
      {
        "qty": 1000,
        "val": 2.84
      },
      {
        "qty": 1500,
        "val": 2.66
      }
    ]
  },
    {
    "number": "6776",
    "Name": "test9",    
    "data": [
      {
        "qty": 0,
        "val": 2
      },
      {
        "qty": 100,
        "val": 3
      },
      {
        "qty": 200,
        "val": 4
      },
      {
        "qty": 300,
        "val": 5
      }
    ]
  },
  {
    "number": "7896",
    "Name": "test4",    
    "data": [
      {
        "qty": 0,
        "val": 5.11
      },
      {
        "qty": 500,
        "val": 6.92
      },
      {
        "qty": 1000,
        "val": 3.84
      },
      {
        "qty": 1500,
        "val": 1.66
      }
    ]
  },
  {
    "number": "4567",
    "Name": "test2",    
    "data": [
      {
        "qty": 0,
        "val": 4.11
      },
      {
        "qty": 500,
        "val": 9.92
      },
      {
        "qty": 1000,
        "val": 5.84
      },
      {
        "qty": 1500,
        "val": 7.66
      }
    ]
  }
  
]

Answer №1

Implement a key Set collection to efficiently check for existing items in arr2 and filter them out.

arr1Set =  new Set(arr1.map(o => o.number));
let newArry = arr1.concat(...arr2.filter(o => !arr1KeySet.has(o.number)))

let arr1 = [
  {
    "number": "1234",
    "Name": "test",    
    "data": [
      {
        "qty": 0,
        "val": 1.11
      },
      {
        "qty": 500,
        "val": 2.92
      },
      {
        "qty": 1000,
        "val": 2.84
      },
      {
        "qty": 1500,
        "val": 2.66
      }
    ]
  },
    {
    "number": "6776",
    "Name": "test9",    
    "data": [
      {
        "qty": 0,
        "val": 2
      },
      {
        "qty": 100,
        "val": 3
      },
      {
        "qty": 200,
        "val": 4
      },
      {
        "qty": 300,
        "val": 5
      }
    ]
  },
  
]

let arr2 = [
{
    "number": "1234",
    "Name": "test",    
    "data": [
      {
        "qty": 0,
        "val": 1.11
      }
    ]
  },
  {
    "number": "7896",
    "Name": "test4",    
    "data": [
      {
        "qty": 0,
        "val": 5.11
      },
      {
        "qty": 500,
        "val": 6.92
      },
      {
        "qty": 1000,
        "val": 3.84
      },
      {
        "qty": 1500,
        "val": 1.66
      }
    ]
  },
  {
    "number": "4567",
    "Name": "test2",    
    "data": [
      {
        "qty": 0,
        "val": 4.11
      },
      {
        "qty": 500,
        "val": 9.92
      },
      {
        "qty": 1000,
        "val": 5.84
      },
      {
        "qty": 1500,
        "val": 7.66
      }
    ]
  }
 ]

let arr1Set =  new Set(arr1.map(o => o.number));
let newArry = arr1.concat(...arr2.filter(o => !arr1Set.has(o.number)))
console.log(newArry);

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 depths of Angular8: Utilizing formControlName with complex nested

After dedicating numerous hours to tackle this issue, I finally came up with a solution for my formGroup setup: this.frameworkForm = this.formBuilder.group({ id: [null], name: ['', Validators.required], active: [true], pa ...

How to choose cypress elements that are text-free using Cypress

Currently, I am troubleshooting an issue with a dropdown menu that allows for invalid selections. Despite being labeled as "unavailable," users are still able to click on these options for the product. <select readonly="" class="size-sele ...

Issue with Angular Ionic HTTP promise functionality not performing as expected

My service retrieves data from an endpoint : Service.ts getAllProducts(){ return new Promise( (resolve, reject) => { this.apiService.get( this.allProducts, `/products`, {} ) .then( data => resolve( data.map( item => this.par ...

Suggestions for managing the window authentication popup in Protractor when working with Cucumber and TypeScript?

I'm a beginner with Protractor and I'm working on a script that needs to handle a window authentication pop-up when clicking on an element. I need to pass my user id and password to access the web page. Can someone guide me on how to handle this ...

Issue with ThreeJs OBJLoader and MTLLoader: materials are loading successfully but not displaying on the object

I'm currently working on integrating a low-poly car model into my Three.JS scene using OBJLoader and MTLLoader. The downloaded model unfortunately lacks textures which makes it challenging to display the materials properly (as shown in the right car o ...

How can Angular JS handle multiple validators being triggered at once?

Hey there, I'm currently working with validators in my Angular form setup. Here's a snippet of how it looks - I utilize Validators.compose to combine custom validators. The errors from these validators are then displayed on the HTML component. My ...

A method to access a stored value in localStorage that does not involve utilizing the __zone_symbol__value property

I am encountering a problem with localStorage. After storing user information in localStorage, I am unable to retrieve it without using the __zone_symbol__value property of the parsed value. This is how I store data into locaStorage localStorage.setItem(& ...

Can you explain the significance of the "@" symbol in the `import from '@/some/path'` statement?

When I use IntelliJ IDEA to develop a web application in TypeScript, the autocomplete feature suggests imports from other files within my project like this: import {Symbol} from '@/components/Symbol'; I am curious about the significance of the @ ...

The element mat-divider in Angular is unrecognized

While testing a popup component in Angular, I encountered an error message that says: 'mat-divider' is not a known element: 1. If 'mat-divider' is an Angular component, then verify that it is part of this module. 2. If ' ...

Is there a way to switch from default export to regular export in TypeScript?

After reading this article and this other one, I came to the conclusion that default export may not be the best approach. However, while trying to refactor my code, I encountered an issue with some variables/objects/functions that were not clearly defined ...

Exploring the Implementation of Routing in AngularJS 2

I recently started working on my first AngularJS 2 application and I am currently in the process of setting up routing. I followed an example from the official AngularJS 2 documentation website to create a simple Product CRUD application, but I'm enco ...

Next.JS-13 detects faulty middleware in App routing

Here is the code snippet from the middleware file: import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; // This function can be marked as `async` if using `await` inside export function middleware ...

Adding an anchor tag to an ngx-datatable-column can be done by utilizing the properties

My task involves loading data from the server and populating the ngx-datatable. When a specific column is clicked (with either a link <a href="randomurl"/> or [routerLink]="randomcomponent"), it should redirect to a different page or display a modal ...

Backend not receiving the request

While all tests pass successfully in Postman, I'm encountering an issue where requests are not reaching the backend when testing from the front-end. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common ...

Kendo's comboBox for local virtualization

Looking to implement virtualization for local data using the kendo object ComboBox. I've tried different methods, but only the current page (first 40 elements) is displayed. I followed a code structure similar to the kendo virtualization tutorial an ...

Apollo Client's useQuery function is causing unnecessary refetches when using Next.js' router.push method

Currently, I'm facing an issue where a query within a useQuery Apollo Client hook is being re-run unnecessarily every time Next.js's router.push function is triggered. The problem code snippet looks like this: const Parent = () => { useQuery ...

What is the best way to manage d.ts files when sharing my TypeScript code on npm?

I recently came across an interesting article on creating strongly-typed npm packages, which can be found here. I've been working on setting up my TypeScript project to publish it to npm, following the guidelines provided in the article. However, one ...

Is it advisable to specify data types for my JSON data in TypeScript?

For the shopping application in my project, I am utilizing a JSON structure to categorize products as either hot or branded. However, I encountered an issue when trying to define a type for the entire JSON object labeled "full". Despite my attempts, it app ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

Mastering the Art of Dynamically Assigning Types in TypeScript

Recently, I encountered a challenge with wrapper function types. I am looking to convert functions with callbacks into promise-based functions. Most of these functions have a similar structure: func({ success:...., fail:...., complete:... }) So, I ...