Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of objects intersection

Tags:

javascript

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"
    }
]
like image 594
DeseaseSparta Avatar asked Apr 27 '16 16:04

DeseaseSparta


People also ask

How do you use intersection in JavaScript?

Example 1: Perform Intersection Using SetThe for...of loop is used to iterate over the second Set elements. The has() method is used to check if the element is in the first Set . If the element is present in the first Set , that element is added to the intersectionResult array using the push() method.


1 Answers

Using filter and some functions

var array1 = [{ "file": "tttt.csv", "media": "tttt" }, { "file": "bob_bob.csv", "media": "bob_bob" }, { "file": "bob1_bob1.csv", "media": "bob1_bob1" }, ];

var array2 = [{ "title": "bob_bob", "version": "bob", "date": "27/4/2016", "selected": false, "file": "bob_bob.csv", "media": "bob_bob", "exists": true }, { "title": "bob1_bob1", "version": "bob", "date": "27/4/2016", "selected": false, "file": "bob1_bob1.csv", "media": "bob_bob", "exists": true }]

var res = array1.filter(n => !array2.some(n2 => n.file == n2.file));

document.write(JSON.stringify(res));

*solution uses ES6 arrow function, it may not work in old browsers

like image 146
isvforall Avatar answered Sep 23 '22 05:09

isvforall