47

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?

3
  • Yep, _.difference Commented Nov 17, 2016 at 13:28
  • 11
    so this was marked duplicate by 6 people? do those 6 people even know the difference between an array of primitives and an array of complex objects? Commented Mar 13, 2019 at 14:58
  • I think lodash _.differenceBy(lodash.com/docs/4.17.15#differenceBy) could help. Commented Feb 28, 2020 at 4:47

3 Answers 3

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

_.differenceWith is only available since 4.0.0 lodash version

Sign up to request clarification or add additional context in comments.

2 Comments

_.differenceWith is only available since 4.0.0 lodash version
did you see he ask about :::: arrays of objects array1 = [obj1,obj2,obj3,obj4] array2 = [obj5,obj5,obj6,obj7]
29

ES6 This will be enough:

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

without includes

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

Plunker for you

2 Comments

can't use your solution since i'am using angular 2 with typescript, includes return an error
this is NOT enough. you are using primitive values in the plunkr, OP is not
8

_.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?

3 Comments

yes this is what i'am trying to achieve, but when i use _difference in the case that my two array are idantical i have array1 as output ! is it normal ?
no... should send you [] (I've tested it now on chrome console in lodash docs...). are you using nodejs or a web browser?
yeah finally it works fine, it was an error made by me . thx for your help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.