Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash / javascript : Compare two collections and return the differences [duplicate]

I have two arrays of objects:

Elements of my tables are not primitive value, but complex objects.

array1 = [obj1,obj2,obj3,obj4]
array2 = [obj5,obj5,obj6,obj7]

I would like to compare two arrays and see if the elements of array2 are already present in array1 then create a new array of the difference.

Any suggestions?

like image 743
Nacim Idjakirene Avatar asked Nov 17 '16 13:11

Nacim Idjakirene


3 Answers

var presents = _.intersectionWith(array1, array2, _.isEqual);
var dif = _.differenceWith(array1, array2, _.isEqual);

_.differenceWith is only available since 4.0.0 lodash version

like image 128
stasovlas Avatar answered Nov 04 '22 10:11

stasovlas


ES6 This will be enough:

array2.filter(e => !array1.includes(e));

without includes

array2.filter(e=> array1.indexOf(e) < 0);

Plunker for you

like image 36
Alex Bykov Avatar answered Nov 04 '22 09:11

Alex Bykov


_.difference gives you only the elements that are in the 1st array but not in the second one, nothing about the elements on the array 2 that are not in the array 1.

Is this what you want to achieve?

like image 8
Matteo Bombelli Avatar answered Nov 04 '22 10:11

Matteo Bombelli