7

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.

2
  • 4
    The answer to your actual question (whether such a function exists) is: no. Commented Jul 23, 2013 at 8:44
  • @FelixKling Ok, thanks, that what I sought Commented Jul 23, 2013 at 8:48

2 Answers 2

35

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]
Sign up to request clarification or add additional context in comments.

6 Comments

Where is the jQuery here?
Hm... I'm not sure that filter will work in IE8 or less without jQuery, but I might be wrong.
Then you should provide jQuery solution, since array.filter() is a prototype method. jQuery method is called $.grep().
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
Never realized $(array1).filter(array2) could do pure array manipulations. That helped!
|
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.