Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 677
JackJack Avatar asked Oct 15 '25 15:10

JackJack


2 Answers

You could use xor from lodash and it will return an empty array if the arrays have the same elements.

const a1= ['a', 'b', 'd']
const a2= ['d', 'b', 'a']
 
_.xor(a1, a2).length;//0
like image 196
Stefan Avatar answered Oct 18 '25 06:10

Stefan


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>
like image 45
Ori Drori Avatar answered Oct 18 '25 07:10

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!