Reputation: 425
I am able to get the difference between two arrays of objects using _.differenceWith like this:
_.differenceWith(arr1, arr2, _.isEqual)
Suppose I have arr1
and arr2
as:
let arr1= [
{
id:1,
val1:{
pre:1,
foo:2
}
}
]
let arr2= [
{
id:3,
val1:{
pre:1,
foo:2
}
},
]
The id
s are different, but the val1
properties are same.
So, I want to compare the arrays excluding id
.
How can I achieve this using lodash or simple JS?
Upvotes: 1
Views: 3218
Reputation: 24191
You can use _.omit
to omit id in when doing isEqual..
eg.
let arr1= [
{id:1, val1:{ pre:1, foo:2 }},
{id: 4, val1: { pre: 3, addThis: 'just to check' }}
];
let arr2= [{ id:3, val1:{ pre:1, foo:2 }}];
console.log(_.differenceWith(arr1, arr2, (a, b) => {
return _.isEqual(
_.omit(a, ['id']),
_.omit(b, ['id'])
)
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
Upvotes: 2
Reputation: 191976
Use the _.differenceWith()
comparator function to compare the val1
property of the objects:
const arr1 = [{"id":1,"val1":{"pre":1,"foo":2}}]
const arr2 = [{"id":3,"val1":{"pre":1,"foo":2}}]
const result = _.differenceWith(arr1, arr2, (a, b) => _.isEqual(a.val1, b.val1))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Upvotes: 1