Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lodash intersectionWith to compare and find same attribute with same value among two arrays with difference structure?

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?

like image 715
Ezeewei Avatar asked Jan 06 '23 23:01

Ezeewei


2 Answers

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>
like image 90
ryeballar Avatar answered Jan 08 '23 13:01

ryeballar


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);
like image 23
awmidas Avatar answered Jan 08 '23 14:01

awmidas