// Return elements of array a that are also in b in linear time:_x000D_
function intersect(a, b) {_x000D_
return a.filter(Set.prototype.has, new Set(b));_x000D_
}_x000D_
_x000D_
// Example:_x000D_
console.log(intersect([1,2,3], [2,3,4,5]));
_x000D_
I recommend above succinct solution which outperforms other implementations on large inputs. If performance on small inputs matters, check the alternatives below.
Alternatives and performance comparison:
See the following snippet for alternative implementations and check https://jsperf.com/array-intersection-comparison for performance comparisons.
function intersect_for(a, b) {_x000D_
const result = [];_x000D_
const alen = a.length;_x000D_
const blen = b.length;_x000D_
for (let i = 0; i < alen; ++i) {_x000D_
const ai = a[i];_x000D_
for (let j = 0; j < blen; ++j) {_x000D_
if (ai === b[j]) {_x000D_
result.push(ai);_x000D_
break;_x000D_
}_x000D_
}_x000D_
} _x000D_
return result;_x000D_
}_x000D_
_x000D_
function intersect_filter_indexOf(a, b) {_x000D_
return a.filter(el => b.indexOf(el) !== -1);_x000D_
}_x000D_
_x000D_
function intersect_filter_in(a, b) {_x000D_
const map = b.reduce((map, el) => {map[el] = true; return map}, {});_x000D_
return a.filter(el => el in map);_x000D_
}_x000D_
_x000D_
function intersect_for_in(a, b) {_x000D_
const result = [];_x000D_
const map = {};_x000D_
for (let i = 0, length = b.length; i < length; ++i) {_x000D_
map[b[i]] = true;_x000D_
}_x000D_
for (let i = 0, length = a.length; i < length; ++i) {_x000D_
if (a[i] in map) result.push(a[i]);_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
function intersect_filter_includes(a, b) {_x000D_
return a.filter(el => b.includes(el));_x000D_
}_x000D_
_x000D_
function intersect_filter_has_this(a, b) {_x000D_
return a.filter(Set.prototype.has, new Set(b));_x000D_
}_x000D_
_x000D_
function intersect_filter_has_arrow(a, b) {_x000D_
const set = new Set(b);_x000D_
return a.filter(el => set.has(el));_x000D_
}_x000D_
_x000D_
function intersect_for_has(a, b) {_x000D_
const result = [];_x000D_
const set = new Set(b);_x000D_
for (let i = 0, length = a.length; i < length; ++i) {_x000D_
if (set.has(a[i])) result.push(a[i]);_x000D_
}_x000D_
return result;_x000D_
}
_x000D_
Results in Firefox 53:
Ops/sec on large arrays (10,000 elements):
filter + has (this) 523 (this answer)
for + has 482
for-loop + in 279
filter + in 242
for-loops 24
filter + includes 14
filter + indexOf 10
Ops/sec on small arrays (100 elements):
for-loop + in 384,426
filter + in 192,066
for-loops 159,137
filter + includes 104,068
filter + indexOf 71,598
filter + has (this) 43,531 (this answer)
filter + has (arrow function) 35,588