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 :
JavaScript
x
8
1
array1 = array1.filter(function(n) {
2
for(var i=0; i < array2.length; i++){
3
if(n.file != array2[i].file){
4
return n;
5
}
6
}
7
});
8
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 :
JavaScript
1
7
1
[
2
{
3
"file": "tttt.csv",
4
"media": "tttt"
5
}
6
]
7
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:
JavaScript
1
9
1
array1 = array1.filter(function(n) {
2
for(var i=0; i < array2.length; i++){
3
if(n.file == array2[i].file){
4
return false;
5
}
6
}
7
return true;
8
});
9
Untested. That returns false
once it find the element in array2 and otherwise if it wasn’t found returns true
.