Effortless Array Intersection in JavaScript
Array intersection is a fundamental operation in programming. Given two arrays, the intersection returns a new array containing only the elements that are common to both. In JavaScript, implementing this operation library-free is surprisingly straightforward.
Solution
The simplest and most concise way to achieve array intersection in JavaScript is by utilizing the power of Array.prototype.filter and Array.prototype.includes. This approach avoids the need for complex loops or external dependencies.
const intersection = (array1, array2) => { return array1.filter((value) => array2.includes(value)); };
Alternatively, for older browsers that may not support arrow functions, you can use the following code:
const intersection = (array1, array2) => { return array1.filter(function(n) { return array2.indexOf(n) !== -1; }); };
Example
To illustrate the effectiveness of this solution, consider the following example:
console.log(intersection([1, 2, 3], [2, 3, 4, 5])); // [2, 3]
The intersection function correctly returns an array containing the common elements, [2, 3], as expected.
Note
It's crucial to note that both Array.prototype.includes and Array.prototype.indexOf compare elements in the array using strict equality (===), which means if the arrays contain complex objects, the comparison will only match object references, not their content. To handle this use case, consider using Array.prototype.some to specify custom comparison logic.
The above is the detailed content of How Can I Efficiently Find the Intersection of Two Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!