1

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?

1
  • Try: const arr = arr2.filter(i => arr1.includes(i.id)). Since, includes is an array method and i doesn't have id Commented Dec 17, 2019 at 10:14

6 Answers 6

2

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); 
})
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

0

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)

Comments

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

1 Comment

add relavant text to explain your answer
0

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

1 Comment

Wouldn't Array.prototype.some() be more appropriate?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.