Simplest Code for Array Intersection in Javascript
Array intersections are a common operation in programming, where you want to find the elements that exist in both arrays. In Javascript, a library-free implementation can be achieved using the following approaches:
Firstly, leverage a combination of Array.prototype.filter and Array.prototype.includes:
const filteredArray = array1.filter(value => array2.includes(value));
For older browsers, you can utilize Array.prototype.indexOf and a non-arrow function instead:
var filteredArray = array1.filter(function(n) { return array2.indexOf(n) !== -1; });
It's important to note that both .includes and .indexOf utilize === for element comparison. Therefore, when dealing with arrays containing objects, only object references are compared. If you require custom comparison logic, consider using Array.prototype.some instead.
The above is the detailed content of What's the Simplest JavaScript Code for Finding Array Intersections?. For more information, please follow other related articles on the PHP Chinese website!