capuche
capuche

Reputation: 55

remove the intersection in 2 arrays in typescript/javascript

I have 2 object lists with 2 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'}];

I want to delete the objects inside each list with the intersection over the uuid.

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

in the code below I am extracting the uuids from the obj lists and put them into a new array each

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']

then use lodash to get the intersection:

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

we can use the list e to do the remove on users1 and users2

but then I am not really sure on how to do the delete

any idea, suggestion or example would be appreciated?

Upvotes: 1

Views: 560

Answers (1)

Ori Drori
Ori Drori

Reputation: 192607

Removing the intersection is actually finding the difference - use _.differenceBy() to filter each user by finding the items with a uuid that doesn't exist on the other user:

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>

Upvotes: 2

Related Questions