简体   繁体   English

查找数组中不包含在另一个对象数组中的元素

[英]Find elements in an array not contained in another array of objects

I have an array arr1 = [1,2,3,4,5] There is another array of objects arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]我有一个数组arr1 = [1,2,3,4,5]还有另一个对象数组arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]

I am looking for find elements in arr1 which are not in arr2 .我正在寻找arr1中不在arr2元素。 The expected output is [1,3,5]预期输出为[1,3,5]

I tried the following but it doesn't work.我尝试了以下但它不起作用。

const arr = arr1.filter(i => arr2.includes(i.id));

Can you please help?你能帮忙吗?

A solution with O(arr2.length) + O(arr1.length) complexity in Vanilla JS Vanilla JS 中 O(arr2.length) + O(arr1.length) 复杂度的解决方案

var arr1= [1,2,3,4,5]; 
var arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}];

var tmp = arr2.reduce(function (acc, obj) { 
    acc[obj['id']] = true; 
    return acc; 
}, {});

var result = arr1.filter(function(nr) { 
    return !tmp.hasOwnProperty(nr); 
})

arr2 is an array of objects, so arr2.includes(i.id) doesn't work because i (an item from arr1 ) is a number , which doesn't have an id property, and because arr2 is an array of objects. arr2是一个对象数组,因此arr2.includes(i.id)不起作用,因为i (来自arr1的项目)是一个数字,它没有id属性,并且因为arr2是一个对象数组。

Turn arr2 's id s into a Set first, then check whether the set contains the item being iterated over:先将arr2id转成 Set,然后检查该集合是否包含被迭代的项目:

 const arr1 = [1,2,3,4,5]; const arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]; const ids = new Set(arr2.map(({ id }) => id)); const filtered = arr1.filter(num => !ids.has(num)); console.log(filtered);

You can try with Array.prototype.some() :您可以尝试使用Array.prototype.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. some()方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。 It returns a Boolean value.它返回一个布尔值。

 const arr1 = [1,2,3,4,5] const arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}] const arr = arr1.filter(i => !arr2.some(j => j.id == i)); console.log(arr);

We can use the filter method like below to check the condition required我们可以使用下面的过滤方法来检查所需的条件

    var arr1 = [1, 2, 3, 4, 5]
    var arr2 = [{ 'id': 2, 'name': 'A' }, { 'id': 4, 'name': 'B' }]
    var ids = [];
    arr2.forEach(element => {
        ids.push(element['id'])
    });

    var result = arr1.filter(s => ids.indexOf(s) < 0)
    console.log(result)
let arr1= [1,2,3,4,5]; 
let arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]


let arr2Ids=arr2.map(item=>item.id); 
let result=arr1.filter(n => !arr2Ids.includes(n));

您可以在arr2上使用 find 而不是包含,因为arr2由对象组成

const arr = arr1.filter(i => !arr2.find(e => e.id===i));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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