Array of intersection of objects

I have two lists of objects, and I would like to filter mine array1without a key file, which are in array2:

What I've done:

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

This returns exactly array1, whereas if I replaced !=with ==, it will return the objects that I want to get rid of.

I do not understand why.

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

So in the end I would like to end this array:

[
    {
     "file": "tttt.csv",
     "media": "tttt"
    }
]
+1
source share
4 answers

Your function does not do what you want, because it does not return falsefor values ​​that you do not want, and truefor those that 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;
});

. false, 2, , , true.

+3

, .

var array1 = [{ "file": "tttt.csv", "media": "tttt" }, { "file": "bob_bob.csv", "media": "bob_bob" }, { "file": "bob1_bob1.csv", "media": "bob1_bob1" }],
    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 }],
    temp = Object.create(null);

array2.forEach(function (a) {
    temp[a.file] = true;
});

array1 = array1.filter(function (a) {
    return !temp[a.file];
});

document.write('<pre>' + JSON.stringify(array1, 0, 4) + '</pre>');
Hide result
+2

filter some

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

* ES6 arrow,

+2

, , . array.some true ( - true ) false. , . !

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 result = array1.filter(function(n1) {
  return !(array2.some(function(n2){
  	return n1.file === n2.file;
  }))
});

document.write('<pre>' + JSON.stringify(result))
Hide result
+1

All Articles