检查一个数组中的对象是否包含在另一个对象数组中

时间:2020-04-20 06:48:29

标签: javascript algorithm

我们有2个数组

const arr1 = [{color: 'red', shape: 'square'}, {color: 'blue', shape: 'circle'}, {color: 'green', shape: 'square}]
const arr2 = [{color: 'red', shape: 'circle'}, {color: 'blue', shape: 'circle'}]

我想检查arr1内是否包含arr2中的至少一项(如果是,则返回bool值)。到目前为止,我尝试了arr2.some(item => arr1.includes(item)),但这似乎不起作用。

4 个答案:

答案 0 :(得分:1)

您可以使用此代码arr2.some(item => arr1.find(e => JSON.stringify(e)=== JSON.stringify(item))

答案 1 :(得分:0)

Array.prototype.includes检查是否相等,因此对于原始值很有用。要检查深度是否相等(对于数组和对象),可以使用find方法。因此正确的解决方案是:

arr2.some(item => arr1.find(e=>e.color==item.color&&e.shape==item.shape))

答案 2 :(得分:0)

数组includes()使用引用相等性匹配对象,它不对项目对象的属性进行深度比较。因此,您还需要一个对象匹配器。

const overlap = arr1.some(i1 => arr2.some(i2 => matchObj(i1,i2)));

,您将必须编写matchObj(obj1, obj2)的实现。

您还可以使用lodash的isEqual()intersecttionWith()方法:

const arr1 = [{color: 'red', shape: 'square'}, {color: 'blue', shape: 'circle'}, {color: 'green', shape: 'square'}];
const arr2 = [{color: 'red', shape: 'circle'}, {color: 'blue', shape: 'circle'}];

// check for overlap
const hasCommon = _.some(arr1, i1 => _.some(arr2, i2 => _.isEqual(i1, i2)));
console.log('hasCommon:', hasCommon);

// get common items
const commonItems = _.intersectionWith(arr1, arr2, _.isEqual);
console.log('commonItems:', commonItems);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

答案 3 :(得分:0)

如果对象数组很小,则不要太大。您也可以使用JSON.stringify进行检查。

const arr1_str = JSON.stringify(arr1);
arr2.some(item2 => arr1_str.includes(JSON.stringify(item2)));

const arr1 = [{color: 'red', shape: 'square'}, {color: 'blue', shape: 'circle'}, {color: 'green', shape: 'square'}];
const arr2 = [{color: 'red', shape: 'circle'}, {color: 'blue', shape: 'circle'}];

const arr1_str = JSON.stringify(arr1);
console.log(arr2.some(item2 => arr1_str.includes(JSON.stringify(item2))));