Finding Array Intersections with Minimalistic Code in JavaScript
To determine the shared elements between two arrays in JavaScript without relying on external libraries, a simple approach utilizing built-in array methods is:
const filteredArray = array1.filter(value => array2.includes(value));
If targeting older browsers that lack the "includes" method and arrow functions:
var filteredArray = array1.filter(function(n) { return array2.indexOf(n) !== -1; });
Note that both "includes" and "indexOf" compare array elements via strict equality (===). Consequently, when working with arrays of objects, only object references are contrasted, not their actual values.
To customize the comparison criteria, consider employing Array.prototype.some instead.
The above is the detailed content of How Can I Find the Intersection of Two Arrays in JavaScript Efficiently?. For more information, please follow other related articles on the PHP Chinese website!