Reputation: 123
I have 2 arrays with objects.
const a = [
{
name: 'John'
},
{
name: 'Adam'
}
]
const b = [
{
name: 'Adam'
}
]
I want to get the object is not the same in the array and also get the object that is same in arrays as well.
const same = [
{
name: 'Adam'
}
]
const not_same = [
{
name: 'John'
}
]
Using lodash library is it possible?
Upvotes: 0
Views: 1793
Reputation: 191976
You can use _.partition()
to get two arrays according to a certain criteria:
const a = [{
name: 'John'
},
{
name: 'Adam'
}
];
const b = [{
name: 'Adam'
}];
const bMap = _.keyBy(b, 'name'); // create a map of names in b
const [same, not_same] = _.partition(a, ({ name }) => name in bMap); // partition according to bMap and destructure into 2 arrays
console.log('same: ', same);
console.log('not_same: ', not_same);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Upvotes: 0
Reputation: 97130
You can use intersectionBy
and xorBy
as follows:
const a = [{
name: 'John'
},
{
name: 'Adam'
}
];
const b = [{
name: 'Adam'
}];
console.log(_.intersectionBy(a, b, 'name')); // values present in both arrays
console.log(_.xorBy(a, b, 'name')); // values present in only one of the arrays
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Upvotes: 2