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

最后都变了- 提交于 2019-12-03 11:00:35

问题


I have two array of object :

the element of my table are not primitive value, but complexe objects.

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

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

Any suggestion ?


回答1:


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



回答2:


ES6 This will be enough:

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

without includes

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

Plunker for you




回答3:


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



来源:https://stackoverflow.com/questions/40656124/lodash-javascript-compare-two-collections-and-return-the-differences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!