I have a problem on which I was stuck for awhile but I already solved it but I still need insight as to why it occurs.
The problem wants me to subtract one list from another and return the resulting
array_diff([1,1,2],[1]) == [1]
.
So I decided to use array.filter() for the problem and this is what I came up with:
function array_diff(a, b) {
for (i in b){
a = a.filter(function(c){ if (c != b[i]){ return c; }});
}
return a;
}
It runs fine until the array includes zero.
For example: array_diff([0,3,4],[3])
. I got [4]
instead of [0,4]
. Why is that?
My solution later is to map a new array and filter null val and that works.
function array_diff(a, b) {
for (i in b){
a = a.map(function(c){ if (c != b[i]){ return c; }});
}
var filtered = a.filter(function (el) {
return el != null;
});
return filtered;
}
But why does filter work like that. I would like to know.