简体   繁体   中英

Remove multiple object from array of objects using filter

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?

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

您只需要进行一些迭代即可:

johnRemoved = someArray.filter( obj => !removeArray.some( obj2 => obj.name === obj2.name ));
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;
}, []);

Filter and some :

someArray.filter(function(item) {
    return !removeArray.some(function(r) { return r.name == item.name && r.lines == item.lines })
});

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

That should do the trick.

const removed = someArray.filter((e) => {
    return removeArray.find(r => r.name === e.name) !== undefined;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM