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

10,540

Solution 1

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>

Solution 2

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);
Share:
10,540
Ezeewei
Author by

Ezeewei

Updated on June 19, 2022

Comments

  • Ezeewei
    Ezeewei almost 2 years

    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?