gus
gus

Reputation: 407

Filter one array of elements using another array

I'm a bit more familiar with python, so what is the javascript equivalent of:

In [25]: listA = [1,2,3,4,5,1,1]
In [26]: listB = [1,2]
In [27]: intersect = [element for element in listA if element in listB]
In [28]: intersect

Out[28]: [1, 2, 1, 1]

This is the closest I can get:

var arrA = [1,1,3,4,5,5,6];
var arrB = [1,5];
var arrC = [];
$.each(arrA, function(i,d){ if (arrB.indexOf(d)> -1){arrC.push(d);} ;});

Any comments on preferred methods? I saw this answer, but it was not exactly what I wanted to answer.

Upvotes: 1

Views: 3505

Answers (1)

KooiInc
KooiInc

Reputation: 122906

You could use Array.filter like this:

var aa = [1,2,3,4,5,1,1]
   ,ab = [1,2]
   ,ac = aa.filter(function(a){return ~this.indexOf(a);},ab);
//=> ac is now [1,2,1,1]

Or as extension for Array.prototype

Array.prototype.intersect = function(arr){
 return this.filter(function(a){return ~this.indexOf(a);},arr);
}
// usage
[1,2,3,4,5,1,1].intersect([1,2]); //=> [1,2,1,1]

See MDN for the Array.filter method (also contains a shim for older browsers)

Upvotes: 8

Related Questions