Jquery function to intersect arrays on the same elements

There is a JS or jQuery function to intersect two arrays, for example:

var array1 = [1,2,3,4,5]; var array2 = [2,4,8,9,0]; var result = someFun(array1, array2); //result = [2,4]; 

Of course, I can do it manually, but maybe there is a shorter way.

+4
source share
2 answers

Since you have jQuery tag:

 $(array1).filter(array2); 

Or:

 $.map(array1, function(el){ return $.inArray(el, array2) < 0 ? null : el; }) 

Or (not for IE8 or less):

 array1.filter(function(el) { return array2.indexOf(el) != -1 }); 

Example:

 > array1 = [1,2,3,4,5]; [1, 2, 3, 4, 5] > array2 = [2,4,8,9,0]; [2, 4, 8, 9, 0] > array1.filter(function(el) { return array2.indexOf(el) != -1 }); [2, 4] 
+26
source

This should work

 var alpha = [1, 2, 3, 4, 5, 6], beta = [4, 5, 6, 7, 8, 9]; $.arrayIntersect = function(a, b) { return $.grep(a, function(i) { return $.inArray(i, b) > -1; }); }; console.log( $.arrayIntersect(alpha, beta) ); 

Demo

+1
source

Source: https://habr.com/ru/post/1492900/


All Articles