for example, I have two set of arrays
arr1 = [
{
myName: 'Adam',
mySkill: 'CSS',
},
{
myName: 'Mutalib',
mySkill: 'JavaScript',
},
];
arr2 = [
{
myName: 'Adam',
myWeight: '112',
},
{
myName: 'Habib',
myWeight: '221',
},
];
I try to compare them, and pick the value of myName
that is the same with lodash's intersectionWith
function. But has not been able to by doing
newList.push(intersectionWith(arr1.arr2,isEqual]));
*in this case, result of intersectionWith(arr1.arr2,isEqual])
should be Adam
Any suggestions, solutions, thoughts on how should I proceed further?
Also, previously I was using two forEach
one within another to achieve that... unless that is the best way that I can do about this kind of sorting?
You should use intersectionBy() to get the intersection by attribute.
var result = _.intersectionBy(arr1, arr2, 'myName');
var arr1 = [{
myName: 'Adam',
mySkill: 'CSS',
}, {
myName: 'Mutalib',
mySkill: 'JavaScript',
}];
var arr2 = [{
myName: 'Adam',
myWeight: '112',
}, {
myName: 'Habib',
myWeight: '221',
}];
var result = _.intersectionBy(arr1, arr2, 'myName');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
If you want to extract the intersection with the myName
value only then you can lazily evaluate it with intersectionBy() and map().
var result = _(arr1).intersectionBy(arr2, 'myName').map('myName').value();
var arr1 = [{
myName: 'Adam',
mySkill: 'CSS',
}, {
myName: 'Mutalib',
mySkill: 'JavaScript',
}];
var arr2 = [{
myName: 'Adam',
myWeight: '112',
}, {
myName: 'Habib',
myWeight: '221',
}];
var result = _(arr1).intersectionBy(arr2, 'myName').map('myName').value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
We can do that without using lodash
const intersectionBy = (a, b, fn) => {
const s = new Set(b.map(fn));
return a.filter(x => s.has(fn(x)));
};
Example:
intersectionBy(arr1, arr2, x => x.myName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With