asanas
asanas

Reputation: 4280

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'}]

I am looking for find elements in arr1 which are not in arr2. The expected output is [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?

Upvotes: 1

Views: 220

Answers (6)

Vitalie Maldur
Vitalie Maldur

Reputation: 591

A solution with O(arr2.length) + O(arr1.length) complexity in Vanilla JS

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

Upvotes: 2

Mamun
Mamun

Reputation: 68923

You can try with Array.prototype.some():

The some() method tests whether at least one element in the array passes the test implemented by the provided function. 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);

Upvotes: 1

Mahamadou DOUMBIA
Mahamadou DOUMBIA

Reputation: 81

You can use find on arr2 instead of includes since arr2 is composed of object

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

Upvotes: 0

Zahidur Rahman
Zahidur Rahman

Reputation: 1718

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

Upvotes: 0

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

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)

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370979

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.

Turn arr2's ids into a Set first, then check whether the set contains the item being iterated over:

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

Upvotes: 1

Related Questions