Calculate the difference between two arrays containing objects using ES6 or TypeScript

I am faced with a challenge involving two arrays:

  arr1 = [{
      id: 1,
      name: 'Diego',
      age: 23
  }, {
      id: 2,
      name: 'Brian',
      age: 18
  }]

  arr2 = [{
      id: 1,
      name: 'Diego',
      age: 23
  }, {
      id: 2,
      name: 'Brian',
      age: 18
  }, {
      id: 3,
      name: 'Pikachu',
      age: 88
  }]

My goal is to find the difference between these arrays, resulting in:

arr3 [{id:3, name: 'Pikachu', age: 88}]

Is there a solution to this problem using ES6 or TypeScript?

I attempted to use SET, but unfortunately, it did not work as expected.

Answer №1

Here is a potential solution:

const getUniqueItems = (arr1, arr2) => {
  let ids1 = arr1.map(item => item.id);
  let ids2 = arr2.map(item => item.id);

  let diff = ids1.map((id, index) => {
    if (ids2.indexOf(id) < 0) {
      return arr1[index];
    }
  }).concat(ids2.map((id, index) => {
    if (ids1.indexOf(id) < 0) {
      return arr2[index];
    }
  })).filter(item => item != undefined);

  return diff;
};

// You can test this function by providing two arrays as arguments

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

How can I conceal an element upon page load using Ionic framework?

index.component.ts initialize() { // Execute necessary functions after loading this.index.ready().then(() => { if(this.index.is('core')){ // this.menu.enable(false, 'mobileOnlyPages'); }else{ ...

Deciphering the outcomes of Promise versus Observables

Query: Methodology fetchDataQuery(): any { let query = new Query((resolve, reject) => { resolve([ { name: 'Apple', type: 'fruit' }, { name: 'Banana', type: 'fruit' } ]); }); ...

What are some effective methods for populating my imageViews without causing them to crash with the error message "Array index out of range

I am currently working on a project where I have 2 view controllers. One of them is an AVCaptureSession responsible for capturing images. My goal is to add each picture I take and select the 'Yes' option to an 'imageArray' and then disp ...

Is there a method to enable autoplay for videos with sound in Chrome while using Angular?

Currently, I am developing a spa where I need to display a banner video at the top of the website. Is there a way to automatically unmute the audio when the video is loading initially? I have attempted to unmute the video and override it, but unfortunatel ...

Issue with Angular 5 HttpClient - PUT request not working in Firefox, however functions correctly in Chrome

Currently in the process of developing a website with Angular 5 and CouchDB. One of my methods in database.service.ts looks like this: import {HttpClient} from '@angular/common/http'; const auth = my database adress; constructor(private http: Ht ...

How can one dynamically update a page in Angular when the path is changed?

I am facing a pagination issue in Angular. Here is my HTML code: <!-- A div element for pagination part at the bottom of the page --> <div style="margin-left: 50%; margin-top: 20px; margin-bottom: 20px"> <ul class="paginat ...

Issue with hydration when logging in with Next-Auth in NextJS 13.4

Step-by-step Instructions: 'node -v' -> v18.16.1 'npx -v' -> 9.8.0 To start, I created a new Next.js app by running npx create-next-app@latest in the terminal within my app folder. Here is a link to the package.json file. Nex ...

Tips for arranging a group of objects based on a nested key within each object

i have a collection of objects that I need to sort based on their id. here is the information: { 1918: { id: "1544596802835", item_id: "1918", label: "Soft Touch Salt Free Mint 500 ml (000001400045)", combo_items: false } 6325: { ...

Avoiding reloading of iframe when switching between components in ReactJS

I am facing an issue with my main component that contains two child components. These child components have an array of iframe and we switch between them based on certain conditions. The problem arises when the iframe's reload every time we move betwe ...

Transforming JSON in Node.js based on JSON key

I am having trouble transforming the JSON result below into a filtered format. const result = [ { id: 'e7a51e2a-384c-41ea-960c-bcd00c797629', type: 'Interstitial (320x480)', country: 'ABC', enabled: true, ...

developing a collection of Material UI text fields

My goal is to construct an accordion containing several textfield mui-components. I have developed a unique render function incorporating all the essential tags and syntax for creating a text field component. Now, I am looking to generate an array of text ...

In Swift, generate a random unique element from an Array until every item has been selected

A unique challenge I am facing involves an array called `notebookCovers` with various cover elements. Additionally, there is a `UIButton` in my app interface that, when pressed, should display a new image using one of the elements from the array. My objec ...

Show Timing on the Y-Axis - Bubble Graph

Recently, I stumbled upon the Bubble Chart feature in ng2-charts. I am trying to display data based on time on the Y-axis and values on the X-axis. My dataset consists of x:[10,35,60], y:["7.00 AM"], with r having the same value as x. However, the sample d ...

Identifying common words in an array of strings and generating a new array containing those words along with their frequency

I have been working on a function that compares a list of words with each other. If the words are similar or one is a substring of the other, it will return the count of how many words are alike. If no matches are found, it will return -1. When I tested t ...

Extending the declaration of JavaScript native methods is not possible when using TypeScript

When attempting to enhance the JS native String class by adding a new method, I encounter error TS2339. interface String { transl(): string; } String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'St ...

The width of the Ion-slide is dynamically determined by the styling

After transitioning my Ionic 2 project to Ionic 3, I encountered issues with ion-slides which are affecting my app's functionality. Upon app loading, specific widths are being defined in the style tags on the slides, disrupting the intended styling. ...

The property you are trying to access is not defined on the enum type in Types

Looking to revise the TypeScript syntax of a lesson found at this link. I am aiming to extract a specific type from a union type using the following syntax: Actions['type'][ActionTypes.FEED_CREATE_POST] The available action types are defined a ...

Exclude weekends from DateTime

Currently working on a task list and aiming to set the default date to 3 days from now, excluding weekends. Utilizing Vue and thinking a computed property might be the solution? DateTime.utc().plus({ days: 3 }).toFormat('yyyy-MM-dd HH:mm:ss'), ...

I'm trying to use the Tailwindcss Outline feature, but it doesn't seem to be working properly

I'm struggling to understand why the background color is displaying properly while the outline color is not. Here's the code snippet I'm referring to: <span className={ ` block w-4 h-4 bg-${legend[key as keyof typeof legend].col ...

Exploring different techniques for filling structures with fixed data in C

Currently, I am populating an array with data to be transmitted via I2C. The code snippet provided below outlines my approach, but I find it quite messy. I would appreciate any suggestions for a cleaner and more efficient method. Thank you in advance! #d ...