user5417542
user5417542

Reputation: 3386

Find difference between two arrays

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 compare one value of the array. This currently compares the complete objects. I only need to compare the id property.

Upvotes: 2

Views: 7869

Answers (1)

styfle
styfle

Reputation: 24720

This 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 comparison 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);

Upvotes: 5

Related Questions