Reputation: 1964
Given,
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Brian",lines:"3,9,62,36" }];
removeArray = [{name:"Kristian", lines:"2,5,10"},
{name:"Brian",lines:"3,9,62,36" }];
How do I remove objects of removeArray from someArray? I can remove a single object:
johnRemoved = someArray.filter(function(el) {
return el.name !== "John";
});
However, instead of comparing someArray names to a string, I'd like to compare them to names in removeArray. Can it be done with a second filter method or does it have to be a for loop?
Upvotes: 3
Views: 9061
Reputation: 1964
I like the answers given here. I wanted to add my own as well.
1 - Two Array.prototype.filter() methods, first filter used for iteration:
removeArray.filter(function(ra) {
someArray = someArray.filter(function(sa) {
return sa.name !== ra.name;
});
});
2 - first iteration can be replaced by for...of loop
for (let item of removeArray){
3- or by Array.prototype.forEach()
removeArray.forEach(function(ra) {
4- as dubbha, Adam and Jonas w mentioned, Array.prototype.some():
someArray.filter(i => !removeArray.some(j => j.name === i.name));
5- lastly trincot's answer was interesting for me:
someArray = someArray.filter(function(obj) {
return !this.has(obj.name);
}, new Set(removeArray.map(obj => obj.name)));
Upvotes: 2
Reputation: 81
someArray.filter(i => !removeArray.map(j => j.name).includes(i.name));
or if you don't want to go beyond ES6 with includes
:
someArray.filter(i => !removeArray.some(j => j.name === i.name));
or using reduce
:
someArray.reduce((acc, i) => {
!removeArray.some(j => j.name === i.name) && acc.push(i);
return acc;
}, []);
Upvotes: 1
Reputation: 55643
someArray.filter(function(item) {
return !removeArray.some(function(r) { return r.name == item.name && r.lines == item.lines })
});
Upvotes: 1
Reputation: 2007
That should do the trick.
const removed = someArray.filter((e) => {
return removeArray.find(r => r.name === e.name) !== undefined;
});
Upvotes: 0
Reputation: 138277
You just need a second some iteration:
johnRemoved = someArray.filter( obj => !removeArray.some( obj2 => obj.name === obj2.name ));
Upvotes: 4
Reputation: 350300
You could use filter
with the this
object equal to the set of names that need removal (a Set
for efficiency):
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Brian",lines:"3,9,62,36" }];
removeArray = [{name:"Kristian", lines:"2,5,10"},
{name:"Brian",lines:"3,9,62,36" }];
someArray = someArray.filter(function(obj) {
return !this.has(obj.name);
}, new Set(removeArray.map(obj => obj.name)));
console.log(someArray);
Upvotes: 2