简体   繁体   中英

Find intersection of 2 arrays containing slightly different objects

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM