Search code examples
javascriptarray-filter

Why the filter method does not return the number 0


When I use filter, the number 0 is not included in the new array:

function arrayDiff(a, b) {
   return a.filter(value => {
       if(!b.includes(value)){
        return value;
      }; 
   });
}

array_diff([1, 2, 0, 4, 2, 6, 4, 1, 4, 0] ,[2,5]);

The returned value is: [1, 4, 6, 4, 1, 4]. See how 0 is missing.

I also tried to return only the number 0, but the empty array was returned.

How can I fix the .filter to include 0 in the result successfully?


Solution

  • 0 is falsey, so when you return value, if value is falsey, it won't be included in the resulting array. Return true instead - or, even easier, just return !b.includes(value):

    function array_diff(a, b) {
       return a.filter(value => !b.includes(value));
    }
    
    console.log(array_diff([1, 2, 0, 4, 2, 6, 4, 1, 4, 0] ,[2,5]));

    (also note that you need to use the same function name when declaring the function and invoking it - either use array_diff for both, or arrayDiff for both)

    You can reduce the computational complexity of the algorithm from O(n ^ 2) to O(n) by using a Set instead, if you want. Set.has is O(1), whereas Array.includes is O(n):

    function array_diff(a, b) {
      const set = new Set(b);
      return a.filter(value => !set.has(value));
    }
    
    console.log(array_diff([1, 2, 0, 4, 2, 6, 4, 1, 4, 0] ,[2,5]));