Search code examples
lodash

I am trying to implement lodash _.difference(array, [values]) using .filter() method


The method/function needs to return an array that has elements in the 1st array that are not present in the second array.

like,

var arr1 = [1,2,3];
var arr2 = [2,3,4,5,6];

should return [1]; and I need to do this using .filter() method!


Solution

  • You can use Array.filter() with Array.includes():

    const arr1 = [1,2,3];
    const arr2 = [2,3,4,5,6];
    
    const difference = (a, b) => a.filter(item => !b.includes(item));
      
    const result = difference(arr1, arr2);
    
    console.log(result);