Search code examples
javascriptlodash

How to compare two arrays using lodash (the order matters)


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

I want to compare arr2 to arr1. But the methods difference() and intersection() only seem to find if the two arrays have the same elements or not. I want to compare the two arrays spot by spot like arr1[0] to arr2[0], arr1[1] to arr2[1]. And it should show:

intersection: 6,7,9
difference: 1,3,4,5

How can I achieve this?


Solution

  • You can do this in lodash by zipping both arrays, filtering, and than taking the last item of each pair. The comperator for intersection is that the pair is equal. The comperator for difference is that the pair are not equal.

    const arr1 = [3,4,5,6,7,1,9];
    const arr2 = [1,3,4,6,7,5,9];
    
    const compare = (comperator) => (arr1, arr2) => 
      _.zip(arr1, arr2)
      .filter(comperator)
      .map(_.last);
    
    const eq = _.spread(_.eq);
    
    const intersection = compare(eq);
      
    const difference = compare(_.negate(eq));
    
    console.log('intersection ', intersection(arr1, arr2));
    console.log('difference ', difference(arr1, arr2));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>