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

Typescript - filtering out null values from JSON object

I am facing an issue with my service method that saves a date on the server. When this method sends the date to the server, it includes fields with null values in the JSON. How can I exclude these fields with null values? public create<T>(post: any) ...

Tips for Loading a Selected Option from an Ajax Call in Angular JS on Page Load

How do I automatically set the selected option from an ajax call when the page loads? I am fetching zones using an ajax call and I want to trigger the change function of the zones on page load in order to set the selected option of the cities select box. ...

What techniques can I employ to ensure that withLatestFrom() effectively interacts with itself?

In my program, I have an intermediate stream that is connected to a source, but it can also trigger events from other sources (such as user input). In another part of my code, there is a derived stream that needs to compare new data from the intermediate w ...

Tic-Tac-Toe: The square's value stays unchangeable

Currently, I am working on creating a tic-tac-toe game using pure vanilla Javascript, so I am aiming to keep it as simple as possible. I have run into an issue and need some guidance. The main requirement is that once a square has been clicked and filled ...

Setting minimum or maximum dates in jquery-simple-datetimepicker is proving to be challenging

Currently, I am utilizing the following library: In this jsfiddle example: http://jsfiddle.net/3SNEq/2/, everything works perfectly when setting minDate or MaxDate directly in the appendDtpicker method. However, when trying to use handleDtpicker like thi ...

Static response is the way to go! Asynchronous responses just don't cut it

Currently in the process of developing an angular directive for displaying real-time charts. Below is the code snippet that encompasses everything, including link: function() { }, within the directive. Here's the code for a static directive that func ...

Combine multiple arrays of JSON objects into a single array while ensuring no duplicates

Trying to combine two JSON arrays into one without duplicates based on date. The jQuery extend() function isn't doing the trick, so looking for an alternative solution that avoids nested $.each statements due to potential large dataset size... [ ...

How to transfer data from PHP to JavaScript using Ajax in the webpage_BODY

I am extracting data from my Controller and passing it to a Javascript file via the Ajax success function. This data is then utilized to create charts. Here is an example of my controller logic: $result =array( "PourcentageCommande" => $Pourcen ...

The Uib-Dropdown functionality is not functioning properly when placed within the body of an HTML view

After correctly installing the following dependencies: "ui-bootstrap": "0.12.2", "ngAnimate": "1.5.5", "AngularJs": "1.5.5 I encountered an issue with creating a dropdown menu in my HTML view. Despite no visible errors and successful implementati ...

Storing each item in its own document within a Firebase collection

I have a feature where users input their sitemap and it generates all the links in the sitemap. How can I then store each of those links in separate documents within a specific collection on Firebase? Below is the current function used to set data in Fir ...

Execute an AJAX request in JavaScript without using string concatenation

On my webpage, users input code in a programming language which can be over 2000 characters long and include any characters. When they press the send button, the code is sent to a server-side script file using JavaScript AJAX. Currently, I am using the fo ...

How do the scopes of a controller and a directive's controller differ from each other?

Can you explain the difference between a controller and a directive's controller in terms of scope? I'm struggling to grasp the distinction and whether it's necessary to create controllers within the DDO for my directives. In the code snipp ...

Sorting and dividing an Array using Angular

Forgive me in advance if this sounds like a naive question, as Angular and Typescript are not my strong suits. I am assisting a friend with an issue that I can't seem to overcome. I have an array of players that includes details such as first name an ...

The URL provided for the Ajax HTTP request is not accurate

Consider the following JavaScript code: <script type="text/javascript" charset="utf-8> function goForLogin() { var xmlhttp; xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","/account/login",true); xmlhttp.s ...

Scrolling is endless with jCarousel - just press a button to keep moving even when you reach the first or

I seem to be experiencing a problem with jCarousel where, upon starting at the beginning, pressing the left button fails to scroll the carousel. The expected behavior is for the carousel to cycle to the end item when the left button is pressed while the f ...

Having trouble with React Page crashing when trying to access the component state

I'm attempting to create a side-bar menu that swaps out content in a <main> tag when menu buttons are clicked. However, I'm facing an issue where the page becomes unresponsive and eventually crashes due to React issues while trying to read ...

What are the best methods for improving the rendering performance of multiple sphereGeometry objects in three.js?

Looking to improve the rendering performance of sphereGeometry in my three.js program, as it is currently a bottleneck. Here is the JavaScript code I am using: var sphereThree = []; for(var idSphere = 0; idSphere < numSphere; idSphere++){ var spher ...

Saving a complicated schema in Node using Mongoose fails to save or update when encountering an error

Greetings, I am facing challenges while trying to save a complex schema in MongoDB. const itemsSchema =new Schema({ cat: {type: String, required: true}, catItems: [{ items:{type: String}, isActive: {type: Boolean, default: true} }] }) ...

Error message "Uncaught TypeError: Unable to read property 'defaultView' of undefined" was encountered while using Google Maps

I am encountering an issue when attempting to load a Google map in React: "Uncaught TypeError: Cannot read property 'defaultView' of undefined" The problem seems to be isolated within this particular component, as the rest of the app renders su ...

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...