6

Does exists a JS or jQuery function to intersect 2 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];

sure I can make it manually, but maybe exists a shorter way.

cmbuckley
  • 40,217
  • 9
  • 77
  • 91
IgorCh
  • 2,641
  • 5
  • 22
  • 29

2 Answers2

33

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]
mishik
  • 9,973
  • 9
  • 45
  • 67
  • 1
    Where is the jQuery here? – VisioN Jul 23 '13 at 08:40
  • Hm... I'm not sure that `filter` will work in IE8 or less without jQuery, but I might be wrong. – mishik Jul 23 '13 at 08:41
  • Then you should provide jQuery solution, since `array.filter()` is a prototype method. jQuery method is called `$.grep()`. – VisioN Jul 23 '13 at 08:43
  • Not sure what all the fuss is about. I can use "filter", "not", and so on with a jQuery array. no issues. This is the intersection, true, but also answers a more general question – Andrew Apr 30 '14 at 06:24
  • 2
    Never realized `$(array1).filter(array2)` could do pure array manipulations. That helped! – i-- Oct 22 '15 at 13:39
  • You can also get rid of the dependency on the variable array2 in the outer scope using the second argument to filter(): `array1.filter (function (v) { return this.indexOf(v) >= 0; }, array2)` – ragelh Apr 05 '16 at 15:13
1

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

RONE
  • 5,415
  • 9
  • 42
  • 71