简体   繁体   中英

Remove object from array if it is contained in another array

I am trying to remove an object from an array, if that object's property (unique) is included in the other array. I know I can do a nested for-loop like this:

for(i = 0; i < array.length; i++) {
    for(j = 0; j < array2.length; j++) {
        if(array[i].Email === array2[j].Email) {
            //remove array[i] object from the array
        }
    }
}

Or whatever. Something like that. Is there an ES6 filter for that? I can easily do a filter up against a regular array with strings, but doing it with an array of objects is a bit more tricky.

If you are fine using ES6, you can even look into array.find , array.filter or array.some

Array.findIndex

var result = array.filter(x=>{
  return array2.findindex(t=> t.Email === x.Email) === -1
})

Array.some

var result = array.filter(x=>{
  return !array2.some(t=> t.Email === x.Email)
})

Not very optimal, but try this

array = array.filter( function( item ){
  return array2.filter( function( item2 ){
    return item.Email == item2.Email;
  }).length == 0;
});

Try with find as well, it won't iterate all the elements and will break after first match itself

array = array.filter( function( item ){
  return array2.find( function( item2 ){
    return item.Email == item2.Email;
  }) == undefined;
});

You could use a Set with ES6

var array = [/* your data */],
    array2 = [/* your data */],
    set = new Set(...array2.map(a => a.Email));

array = array.filter(a => !set.has(a.Email));

Try this one.... :)

if(array[i].Email === array2[j].Email){
   // splice(Index you want to remove,to witch element)
   array1.splice(i,1);
}

splice() can remove element of your array. You need to pass witch element. witch element is the start of delete. How many elements should delete. That's 1.. :)

How about writing a function, passing the parameters and simply collecting the output?

 function arrNotInArrKey(arr1, arr2, key) { for (var i = 0; i < arr1.length; i++) { for (var j = 0; j < arr2.length; j++) { if (arr1[i][key] === arr2[j][key]) { arr1.splice(i, 1); i--; } } } return arr1; } console.log( arrNotInArrKey([{ name: 1 }, { name: 3 }, { name: 2 }], [{ name: 2 }], "name") ); 

You can use shift function. here it's example.

http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_shift
for(i = 0; i < array.length; i++) {
    for(j = 0; j < array2.length; j++) {
        if(array[i].Email === array2[j].Email) {
            array.shift(array[i].Email);
        }
    }
}

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