Home > Web Front-end > JS Tutorial > How Can I Efficiently Find the Intersection of Two Arrays in JavaScript?

How Can I Efficiently Find the Intersection of Two Arrays in JavaScript?

Mary-Kate Olsen
Release: 2024-12-27 12:44:10
Original
163 people have browsed it

How Can I Efficiently Find the Intersection of Two Arrays in JavaScript?

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));
};
Copy after login

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;
  });
};
Copy after login

Example

To illustrate the effectiveness of this solution, consider the following example:

console.log(intersection([1, 2, 3], [2, 3, 4, 5])); // [2, 3]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template