I have following Plunkr which works perfectly.
It uses the _.differenceWith() function of lodash, in order two save all array values, which are not contained by the two arrays.
var result = _.differenceWith(data, test, _.isEqual);
Now I have two problems:
1.) In our project we use an older Lodash Version where the function differenceWith is not implemented
2.) I only need to pare one value of the array. This currently pares the plete objects. I only need to pare the id property.
I have following Plunkr which works perfectly.
https://plnkr.co/edit/WDjoEK7bAVpKSJbAmB9D?p=preview
It uses the _.differenceWith() function of lodash, in order two save all array values, which are not contained by the two arrays.
var result = _.differenceWith(data, test, _.isEqual);
Now I have two problems:
1.) In our project we use an older Lodash Version where the function differenceWith is not implemented
2.) I only need to pare one value of the array. This currently pares the plete objects. I only need to pare the id property.
Share Improve this question edited Jun 9, 2017 at 13:53 j08691 208k32 gold badges269 silver badges280 bronze badges asked Jun 9, 2017 at 13:51 user5417542user5417542 3,4068 gold badges31 silver badges55 bronze badges 3-
_.filter(arr, x=>x.id="something")
– dandavis Commented Jun 9, 2017 at 13:53 -
The Plunkr doesn't work perfectly. It says
ReferenceError: _ is not defined
. So what is your actual data? The data shown has noid
property. – Jeremy Thille Commented Jun 9, 2017 at 14:10 - Omg so so sorry, somehow there was an error. I updated it. Should work now :/ – user5417542 Commented Jun 9, 2017 at 14:23
1 Answer
Reset to default 5This will find the objects in arr1
that are not in arr2
based on the id
attribute.
var arr1 = [ { "id": "1" }, { "id": "2" }, { "id": "3" } ];
var arr2 = [ { "id": "1" }, { "id": "2" } ];
var result = arr1.filter(o1 => arr2.filter(o2 => o2.id === o1.id).length === 0);
console.log(result);
Note that this example does not require lodash.
If you want to use a different parison instead of id
, you can change the o2.id === o1.id
part to a different property.
Here is a more generic solution:
var arr1 = [ { "name": "a" }, { "name": "b" }, { "name": "c" } ];
var arr2 = [ { "name": "a" }, { "name": "c" } ];
function differenceWith(a1, a2, prop) {
return a1.filter(o1 => a2.filter(o2 => o2[prop] === o1[prop]).length === 0);
}
var result = differenceWith(arr1, arr2, 'name');
console.log(result);