-1

I'm trying to find the intersection from 2 different arrays that contain slightly different objects.

For example:

  const  arr1 = [  
       {  
          "number":"1234",
          "id":"34782",
          "firstName":"John",
          "lastName":"Smith",
          "email":"test1@test.com",
       },
       {  
          "number":"1232",
          "id":"34783",
          "firstName":"Chad",
          "lastName":"Baker",
          "email":"test2@test.com",
       }
    ];
    
  const  arr2 = [  
       {  
          "uuid":"0123",
          "firstName":"John",
          "lastName":"Smith",
          "title":"Director"
       },
       {  
          "uuid":"0125",
          "firstName":"Sam",
          "lastName":"Hurst",
          "title":"Manager"
       }
    ]
const arr3 = arr1.filter(object => arr2.includes(object));

console.log(arr3);

I'm trying to create a new array that contains only the objects in arr1 where firstName and lastName values are the same in both arrays.

Desired result from above data:

    arr3 = [  
       {  
          "number":"1234",
          "id":"34782",
          "firstName":"John",
          "lastName":"Smith",
          "email":"test1@test.com",
       },
     ]

since this object's firstName and lastName match in both arr1 and arr2

Right now i have this.arr3 = this.arr1.filter(object => this.arr2.includes(object))

But because arr1 and arr2 contain different objects due to proper names, this doesn't work.

Reactgular
  • 52,335
  • 19
  • 158
  • 208
BIGJOHN
  • 469
  • 4
  • 21
  • 2
    Possible duplicate of [How can I perform an inner join with two object arrays in JavaScript?](https://stackoverflow.com/questions/42429023/how-can-i-perform-an-inner-join-with-two-object-arrays-in-javascript) – dota2pro May 10 '19 at 16:29

2 Answers2

2

Try something like this:

const arr1 = [{
    "number": "1234",
    "id": "34782",
    "firstName": "John",
    "lastName": "Smith",
    "email": "test1@test.com",
  },
  {
    "number": "1232",
    "id": "34783",
    "firstName": "Chad",
    "lastName": "Baker",
    "email": "test2@test.com",
  }
];

const arr2 = [{
    "uuid": "0123",
    "firstName": "John",
    "lastName": "Smith",
    "title": "Director"
  },
  {
    "uuid": "0125",
    "firstName": "Sam",
    "lastName": "Hurst",
    "title": "Manager"
  }
]
const arr3 = arr1.filter(value =>
  arr2.some(value2 =>
    value.firstName === value2.firstName && value.lastName === value2.lastName
  )
);

console.log(arr3);

Basically, use some instead of includes as this allows you to provide a predicate.

dota2pro
  • 7,220
  • 7
  • 44
  • 79
John
  • 2,395
  • 15
  • 21
1

I think you can try this :

arr1.filter(item1 => (arr2.find(item2 => (item2.firstName == item1.firstName && item2.lastName == item1.lastName)) != undefined));

It uses the arr2.find function, to check if it contains some item with same firstName and lastName properties.

AD-DEV
  • 11
  • 4