Skip to content
Advertisement

Array of objects intersection

I have two lists of objects and I would like to filter my array1 without the file key that are in the array2 :

What I did :

array1 = array1.filter(function(n) {
    for(var i=0; i < array2.length; i++){
      if(n.file != array2[i].file){
        return n;
      }
    }
});

This returns exactly the array1 whereas if I replace != with == it returns the objects I want to get rid of.

I don’t understand why.

https://jsfiddle.net/hrzzohnL/1/

So at the end I would like to end with this array :

[
    {
     "file": "tttt.csv",
     "media": "tttt"
    }
]

Advertisement

Answer

Your function doesn’t do what you want as it doesn’t return false for values you don’t want and true for those you want. Consider this:

array1 = array1.filter(function(n) {
    for(var i=0; i < array2.length; i++){
      if(n.file == array2[i].file){
        return false;
      }
    }
    return true;
});

Untested. That returns false once it find the element in array2 and otherwise if it wasn’t found returns true.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement