查找包含稍微不同的对象的2个数组的交集

时间:2019-05-10 16:25:28

标签: javascript arrays

我试图从包含对象略有不同的2个不同数组中找到交集。

例如:

  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);

我正在尝试创建一个仅包含arr1中对象的新数组,其中两个数组中firstNamelastName的值相同。

上述数据的期望结果:

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

因为该对象的名字和姓氏在arr1arr2中都匹配

现在我有this.arr3 = this.arr1.filter(object => this.arr2.includes(object))

但是由于arr1arr2由于专有名称而包含不同的对象,因此无法使用。

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

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);

基本上,使用some代替includes,因为这样可以提供谓词。

答案 1 :(得分:1)

它使用arr2.find函数检查它是否包含某些具有相同firstName和lastName属性的项目。

我认为您可以尝试以下方法:

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(item1 => (arr2.find(item2 => (item2.firstName == item1.firstName && item2.lastName == item1.lastName)) != undefined));


console.log(arr3);