-6

Example

const arr1 = [{id:1,name:'qwerty'},{id:2,name:'qwerty'}]
const arr2 = [{id:1,name:'qwerty'},{id:2,name:'qwerty'},{id:3,name:'qwerty'},{id:4,name:'qwerty'}]

I need to remove all the elements by id from the arr1 that are in the arr2

result

const arr2 = [{id:3,name:'qwerty'},{id:4,name:'qwerty'}]
3

2 Answers 2

3

You could take a Set with all id from arr1 and filter arr2.

This approach

result = arr2.filter(
    (ids => ({ id }) => !ids.has(id))
    (arr1.reduce((s, { id }) => s.add(id), new Set))
);

utilize a closure with an IIFE (immediately-invoked function expression) over an instance of a Set with

arr1.reduce((s, { id }) => s.add(id), new Set)

and this is the value for ids

(ids => callback)(instanceOfSet)

The callback consist only a destructuring for id and a check with Set#has

({ id }) => !ids.has(id)

const
    arr1 = [{ id: 1, name: 'qwerty' }, { id: 2, name: 'qwerty' }],
    arr2 = [{ id: 1, name: 'qwerty' }, { id: 2, name: 'qwerty' }, { id: 3, name: 'qwerty' }, { id: 4, name: 'qwerty' }],
    result = arr2.filter(
        (ids => ({ id }) => !ids.has(id))
        (arr1.reduce((s, { id }) => s.add(id), new Set))
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

2 Comments

wow! Super answer!:) Nina could you, please, explain how does ids work? and why this row works (arr1.reduce((s, { id }) => s.add(id), new Set) at first? and only then this row (ids => ({ id }) => !ids.has(id)) is executed? Thanks in advance!:)
@StepUp, please see edit.
1

You can achieve your required result by using filter and findIndex array prototype.

const arr1 = [{id:1,name:'qwerty'},{id:2,name:'qwerty'}];
const arr2 = [{id:1,name:'qwerty'},{id:2,name:'qwerty'},{id:3,name:'qwerty'},{id:4,name:'qwerty'}];

const res = arr2.filter(value => arr1.findIndex(x => x.id === value.id) === -1);
console.log(res);

Update

The same result could be gained by using find instead of findIndex.

const arr1 = [{id:1,name:'qwerty'},{id:2,name:'qwerty'}];
const arr2 = [{id:1,name:'qwerty'},{id:2,name:'qwerty'},{id:3,name:'qwerty'},{id:4,name:'qwerty'}];

const res = arr2.filter(value => !arr1.find(x => x.id === value.id));
console.log(res);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.