eliminate the common elements between two arrays in typescript/javascript

I have two lists of objects, each containing two fields:

let users1 = [{ name: 'barney',  uuid: 'uuid3'},
              { name: 'barney',  uuid: 'uuid1'},
              { name: 'barney',  uuid: 'uuid2'}];

let users2 = [{ name: 'joe',  uuid:'uuid5'},
              { name: 'joe',  uuid: 'uuid1'}, 
              { name: 'joe',  uuid: 'uuid2'}];

The objective is to remove the objects within each list that share the same UUID value.

let users1 = [{ name: 'barney',  uuid: 'uuid3'}]; // Objects with uuid1 and uuid2 removed
let users2 = [{ name: 'joe',  uuid:'uuid5'}];     // Objects with uuid1 and uuid2 removed

In the following code snippet, I am extracting the UUIDs from the object lists and storing them in separate arrays.

let a =[];  
let b = [];
a = users1.map(s => s.uuid); // UUIDs from list 1 ['uuid3', 'uuid1', 'uuid2']
b = users2.map(s => s.uuid); // UUIDs from list 2 ['uuid5', 'uuid1', 'uuid2']

We can then use a library like lodash to find the intersection:

let e = [];
e = _.intersection(a,b); // Intersection = [uuid1, uuid2] 

The list e can be utilized to delete the corresponding objects from users1 and users2.

If you have any ideas, suggestions, or examples on how to approach this deletion process, please share!

Answer â„–1

To remove the intersection, you can find the difference between two arrays using the _.differenceBy() method. This will filter each user by comparing their uuid values:

const users1 = [{ name: 'barney',  uuid: 'uuid3'},
              { name: 'barney',  uuid: 'uuid1'},
              { name: 'barney',  uuid: 'uuid2'}];

const users2 = [{ name: 'joe',  uuid:'uuid5'},
              { name: 'joe',  uuid: 'uuid1'}, 
              { name: 'joe',  uuid: 'uuid2'}];
              
const user1n = _.differenceBy(users1, users2, 'uuid');
const user2n = _.differenceBy(users2, users1, 'uuid');

console.log(user1n);
console.log(user2n);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

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

Incorporating string input values into a function

I am currently working on a function that retrieves the value of an input upon clicking a button. My goal is to then have another event that will incorporate that value into a function when the button is clicked. var getInput = function() { $('#inpu ...

Navigating through Switch cases and If Statements with multiple arguments can be complex for beginners in the world of JavaScript

Hi there, I have a specific case that I'm struggling to find a solution for. I am using Angular with a Firebase back-end to retrieve true or false values from a variable called ref. The variable contains 4 properties with either true or false values - ...

What might be causing my action function to be triggered during the rendering process?

While working on creating a basic card view in material UI, I encountered an issue where the functions for adding and deleting items seem to be triggered multiple times upon rendering. I am aware that a common reason for this could be using action={myFunc ...

Remove all links with a specific class within a <div> element, excluding the one that was clicked

Is there a way in jQuery to manipulate all links inside a <div> by removing/disabling or changing their classes, except for the one that was clicked? I need to change the class of the clicked link while potentially hiding or altering the others. < ...

The negative z-index is causing issues with my ability to select classes using jQuery

By setting a z-index of -3 for several divs in my background, I thought they wouldn't affect the formatting of elements in the foreground. But now I'm facing an issue where I can't click on those background divs when trying to target them wi ...

Problems related to TypeScript in a callback session

I am currently working on enhancing the API response by adding the unique identifier (id) property during the login process. I followed the recommendation to use callbacks from a discussion on Stack Overflow (Get User ID from session in next-auth client), ...

The functionality of the Vert.x event bus client is limited in Angular 7 when not used within a constructor

I have been attempting to integrate the vertx-eventbus-client.js 3.8.3 into my Angular web project with some success. Initially, the following code worked perfectly: declare const EventBus: any; @Injectable({ providedIn: 'root' }) export cl ...

Deactivate the checkboxes with varying attributes

My goal is to disable checkboxes with different warehouse locations once a warehouse is selected. For instance, if I select California, I want all checkboxes from other states to be disabled. This should be based on the whseID attribute, but I am strugglin ...

JSX conditional rendering not behaving unexpectedly

Having difficulty with a conditional JSX statement causing an element to not display properly unless the window is resized. Please note that it works fine in development mode but does not show correctly after building. The goal is to show navigation links ...

Is there a way to retrieve the $state object from ui router in the console?

I attempted to modify the route from the console by using this method to access the $state object: $inject = angular.injector(['ng', 'ui.router']); $inject.get('$state').go Unfortunately, I encountered an error: Uncaught Er ...

Is it possible to bring in Node's path module by using the import statement like this: `import path from 'path'`?

My preference lies with using the import x from 'y' syntax, however, all that has been brought to my attention online is the usage of const path = require('path'). I am curious if there exists a method of importing the path module util ...

What is the best way to modify the height of a div before fetching an image using Ajax, and then revert it back to its original height once the image has been

Using a form and Ajax, I'm dynamically pulling an image to replace another image in the .results div. Initially, when the image was removed and loaded, the page jumped up and down, so I tried adding a style attribute to set the div height and then rem ...

Struggling to construct a project using parcel, continually encountering issues with unsupported file types

My attempt at creating a project using parcel has hit a snag. Despite diligently following the guidelines provided in my assignment, an error message consistently appears in my terminal each time I initiate the command: parcel src/index.html The error mes ...

Is it possible for a jQuery ajaxSuccess function to detect an AJAX event in a separate JavaScript file? If it is, what steps am I missing?

I've been attempting to initiate a function following an ajax event. I have been informed that despite the ajax event occurring in a different file (on the same server, if that makes a difference) and that the file is javascript, not jquery, "Ajaxsucc ...

Angular - Is there a specific type for the @HostListener event that listens for scrolling on the window?

Encountering certain errors here: 'e.target' is possibly 'null'. Property 'scrollingElement' does not exist on type 'EventTarget'. What should be the designated type for the event parameter in the function onWindow ...

Analyze the information presented in an HTML table and determine the correct response in a Q&A quiz application

I need to compare each row with a specific row and highlight the border accordingly: <table *ngFor="let Question from Questions| paginate: { itemsPerPage: 1, currentPage: p }"> <tr><td>emp.question</td></tr> <tr> ...

Slider for jQuery or Ajax framework

Currently, I am in search of a gauge that contains multiple concentric circles, with each circle displaying values of different entities, similar to the image provided. Each individual needle indicates the value of its corresponding entity. I have come a ...

Switch between various API content upon clicking (JavaScript)

Upon receiving data from an API in JSON format using PHP, I aim to incorporate a filter mechanism for displaying distinct content sourced from the API. For instance, by specifying a filter in my API call, I can retrieve separate datasets such as one with ...

Using globs to specify files for gulp.src

I'm facing a challenge in setting up a glob array for my JavaScript concatenation build task within the Gulp workflow. The file structure I am working with looks like this: ├── about │ └── about.js ├── assets ├── contact â ...

Combining model with a string in an expression in AngularJS version 1

Can this text be transformed into an expression using ecmaScript 2015? The || operator seems to be causing issues. {{ ::$ctrl.realEstateProjectCurrentProduct.housingTax + ' €' || $ctrl.noDataMessage }} ...