Find the distinct elements in two arrays of objects using TypeScript

There are two object arrays available:

first = [
  { "id": "15", "name": "raza" },
  { "id": "1", "name": "sahir" },
  { "id": "54", "name": "ayyan" },
  { "id": "3", "name": "tahir" },
];

 second = [
  { "id": "15", "name": "razi" },
  { "id": "3", "name": "qasim" },
  { "id": "1", "name": "taha" },
];

The goal is to extract unmatched objects from the "first" array based on their id, using the following code:

const result = this.first.filter(e => this.second.some(({id}) => e.id == id ));

The current code retrieves matched objects, but the requirement is to obtain only the unmatched objects.

Answer №1

Does this solution look suitable?

initialList = [
  { "id": "15", "name": "raza" },
  { "id": "1", "name": "sahir" },
  { "id": "54", "name": "ayyan" },
  { "id": "3", "name": "tahir" },
];

updatedList = [
  { "id": "15", "name": "razi" },
  { "id": "3", "name": "qasim" },
  { "id": "1", "name": "taha" },
];

unchangedItems = initialList.filter(item => !updatedList.some(modifiedItem => modifiedItem.id === item.id));

console.log(unchangedItems);

Answer №2

Below is a solution with a time complexity of O(n+m), where n and m represent the lengths of arrays:

let hash={}; secondArray.map(item=>hash[item.id]=1);     // utilize a hash map with ids from secondArray
let finalResult = firstArray.filter(item=>!hash[item.id]);

firstArray = [
  { "id": "15", "name": "raza" },
  { "id": "1", "name": "sahir" },
  { "id": "54", "name": "ayyan" },
  { "id": "3", "name": "tahir" },
];

secondArray = [
  { "id": "15", "name": "razi" },
  { "id": "3", "name": "qasim" },
  { "id": "1", "name": "taha" },
];

let hash = {}; secondArray.map(item=>hash[item.id]=1);     // utilizing hash map with ids from data2
let finalResult = firstArray.filter(item=>!hash[item.id]);

console.log(finalResult);

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

Transform string enum type into a union type comprising enum values

Is there a way to obtain a union type from a typescript string enum? enum MyEnum { A = 'a', // The values are different from the keys, so keyof will not provide a solution. B = 'b', } When working with an enum type like the one sh ...

Troubles with uploading a hefty file

Utilizing the Blazor's InputFile component, I encountered an issue while trying to upload and parse a large Json file from a web view. Upon uploading a 11mb JSON file with approximately 300,000 lines, I received an exception stating that the JSON cont ...

Having difficulty navigating to a different page in Angular 4

I'm currently attempting to transition from a home page (localhost.com) to another page (localhost.com/listing). Although the app compiles correctly, I encounter an issue where nothing changes when I try to navigate to the new page. My approach has m ...

Encountering "undefined" response while retrieving data from service in Angular 2

I'm experiencing an issue with my Angular 2 application where I am making an HTTP call in a service and trying to return the response back to the component. However, when I console log the response, it shows as "undefined". I have added a timeout to e ...

Exploring the Latest Features: Using Angular 7 with Bootstrap Collapse for Dynamic Aria-Controls

I am currently working on creating my own component to use within an *ngFor loop. I am facing an issue where I need a unique value for my Collapse feature. Right now, when I click on the second main row in the table, the collapse feature only shows the inn ...

Issues with loading Datatables table via JSON data in Rails application

I am currently working on a Rails application that is designed to extract data from a JSON file and showcase it in a filterable table. For this purpose, I have decided to utilize datatables.net. However, I have encountered an issue where the table remain ...

How do you properly perform typechecking on a custom fetch function in ReactQuery? I'm encountering an error that states: "....is of an unknown type."

Currently, I am working with typescript + react-query and creating a custom fetch function. I am struggling to properly type this function and encountering a TypeScript error when attempting to use myQuery.error.message const locationQuery: QueryObserverRe ...

Using Node.js to write data to a JSON file

Currently, I am working on a program that scans through an array containing numerous links. It reads through each link, extracts specific text, and then stores it in an output file as JSON. However, I am facing an issue with formatting the JSON file. The ...

The console is being bombarded by ion-range input, resulting in malfunction and unrespons

Recently, I attempted to create a slider for changing text size. Following the documentation, I implemented the following code for a slider with knobs and 3 values: In HTML: <ion-item> <ion-label [ngClass]="size">This is sample t ...

Converting an array of objects to an array of JSON objects in TypeScript

My dilemma lies in the data I have uploaded under the _attachments variable: https://i.sstatic.net/jnFNH.png My aim is to format this data for insertion in the following structure: "_attachments": [ { "container": "string", "fileName": "string" ...

How can the 'env' property in Nuxt.js be utilized to access the new API?

I have been working on creating news web apps that utilize newsapi.org. To protect my API key, I decided to use the env property in Nuxt.Js. However, I am now encountering a 401 status code from the server. Firstly, I created the .env file in my project d ...

What is the process of converting an NSArray from string format to a real Array format?

After parsing a JSON file, the results were stored in an NSArray with the following content: ( { category = Allergies; group = Allergies; name = "Food Allergies"; option = ""; subGroup = ""; type = VARCHAR; }, { categor ...

Encountering an Error in Angular Material 8 due to the Import of the Unforeseen Directive 'MatCard'

I keep encountering the error message displayed above in the console. I am currently working with Angular Material version 8.2.3. In my app.module.ts file, I have the following import statements related to Angular Material: import { MatInputModule, MatBu ...

Retrieve JSON information from an external form in the CodeIgniter framework

I am facing a challenge with my external web form that posts data to my controller URL in the form of a JSON string. My goal is to extract the individual values from the JSON string and store them in my database. However, I am encountering difficulties re ...

Converting Any Type to a Double

I'm currently attempting to parse JSON using the following code: func ltchandler(response: NSURLResponse!, data : NSData!, error : NSError!) { //Is passed the results of a NSURLRequest if ((error) != nil) { //Error Handling Stuff } e ...

Implementing PHP code to fetch a JSON array and store it in a database

I have an invitation table and I am sending the data in JSON format using Postman. I need to send multiple invitations at once, so I want to insert multiple invitations. Is there a way to achieve this? Currently, I have only created a single invitation. ...

Global variable-driven dynamic routing

I have multiple projects set up in a single Angular workspace and I need to dynamically change the routing based on a global variable defined in app.routing.ts. Here is a snippet from my app routing module: import { NgModule } from '@angular/core&ap ...

Tips for showing multiple markers on a Google map using JavaScript based on different addresses rather than latitude and longitude coordinates

Currently, I am utilizing Angular 7 to display markers on a map by providing latitude and longitude coordinates. However, I am curious if there is a way to display multiple markers on the map based on multiple addresses. While I have successfully displaye ...

Display JSON information in the present moment

I am looking to display only 2 results from a JSON file based on the current time. For example, at 11:00 am today, I want to show only the second and third items. JAVASCRIPT $(data.users).each(function() { var output = "<ul><li>" + this.first ...

Is there a universal method to transform the four array values into an array of objects using JavaScript?

Looking to insert data from four array values into an array of objects in JavaScript? // Necessary input columnHeaders=['deviceName','Expected','Actual','Lost'] machine=['machine 1','machine 2&apo ...