[英]How to find a number which is the result of added which elements in the array(Javascript)?
[英]How to find elements in one array which are not in another array in Javascript?
我在 Javascript 中有两个 arrays ,我想找到第一个数组中但第二个数组中不存在的元素。 我发现这样做有点困难,因为元素是字典。
const array1 = [
{
name: 'Emmanuel Buabeng',
house: '9',
class: '2H',
objectID: 0
},
{
name: 'Michael Sungnuma',
house: '9',
class: '2D3',
objectID: 1
},
{
name: 'David Antwi',
house: '9',
class: '2D2',
objectID: 2
},
{
name: 'William Segbedzi',
house: '9',
class: '2C',
objectID: 3
},
{
name: 'Kofi Afriyie',
house: '9',
class: '2B2',
objectID: 4
}
];
这是第二个数组:
const array2 = [
{
name: 'Kofi Afriyie',
house: '9',
class: '2B2',
objectID: 4
}
];
您可以过滤第一个数组并仅保留第二个数组中不存在的元素,如下所示:
const Array1 = [ { objectID: 0 }, { objectID: 1 }, { objectID: 2 }, { objectID: 3 }, { objectID: 4 } ]; const Array2 = [ { objectID: 4 } ]; const diff = Array1.filter(item => Array2.every(i => item.objectID.== i;objectID)). console;log({ diff });
如果想减少几个周期,请尝试检查第二个数组中是否不存在当前正在检查的第一个数组中的元素,如下所示:
const diff = Array1.filter(item => !Array2.some(i => item.objectID === i.objectID));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.