1

I have 2 arrays of objects array 1 and array 2, I want to remove the objects of array 2 from array 1. There can be more than 1 objects that I remove simultaneously.

Data of array 1

let arr1 = [    
    { id: "1", txt: "first"},
    { id: "2", txt: "second"},
    { id: "3", txt: "third"}
 ]

Data of array 2

let arr2 = [
    { id: "2", txt: "second"},
]

Result

{ id: "1", txt: "first"},
{ id: "3", txt: "third"}

2 Answers 2

2

If id property is unique, you can filter out with it.

let arr1 = [    
    { id: "1", txt: "first"},
    { id: "2", txt: "second"},
    { id: "3", txt: "third"}
 ]

let arr2 = [
    { id: "2", txt: "second"},
]

let arr3 = arr1.filter(e1 => !arr2.some(e2 => e2.id === e1.id));

console.log(arr3);

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

2 Comments

I would use arr2.some since it returns a boolean, although the outcome is the same
@HaoWu I Agree. Thanks for your advice.
1

If the requirement is to do a deep equality check between the objects, then we can use lodash's isEqual to do a deep equality check along with Array#filter and Array#some:

let arr1 = [    
    { id: "1", txt: "first"},
    { id: "2", txt: "second"},
    { id: "3", txt: "third"}
 ]

let arr2 = [
    { id: "2", txt: "second"},
]

const filterArr = (arr1, arr2) =>{
  return arr1.filter(a1 => !arr2.some(a2 => _.isEqual(a1, a2)))
}
console.log(filterArr(arr1, arr2))
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Comments

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.