0

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.

jo_va
  • 13,504
  • 3
  • 23
  • 47
H.Le
  • 33
  • 4

2 Answers2

2

The callback to the filter method needs to return a Boolean value, which is used to decide whether to keep the element or not. Your code:

a = a.filter(function(c){ if (c != b[i]){ return c; }}); 

Is returning the element itself. Since JS expects a boolean, it is converting the number to a bool. In particular, 0 is converted to false, so is excluded.

Just do this instead:

a = a.filter(function(c){ return (c != b[i]);}); 
Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34
2

Here is a shorter way to do it, using filter and includes:

const a = [0, 1, 2, 3, 4, 5];
const b = [0, 1, 0, 3, 0, 5];

const arrayDiff = (a, b) => a.filter(elem => !b.includes(elem));

console.log(arrayDiff(a, b));
jo_va
  • 13,504
  • 3
  • 23
  • 47