Home >Web Front-end >JS Tutorial >How Can I Find the Intersection of Two JavaScript Arrays Without Using External Libraries?

How Can I Find the Intersection of Two JavaScript Arrays Without Using External Libraries?

Barbara Streisand
Barbara StreisandOriginal
2024-12-28 17:03:17674browse

How Can I Find the Intersection of Two JavaScript Arrays Without Using External Libraries?

Finding Array Intersections in JavaScript Without Libraries

To determine the intersection of two arrays without the use of additional libraries, consider implementing the following code:

Solution:

Utilize a combination of Array.prototype.filter and Array.prototype.includes methods:

const filteredArray = array1.filter(value => array2.includes(value));

Explanation:

This code filters the elements of array1 based on whether they are also present in array2. The includes method checks for the existence of an element within an array. Therefore, the result is an array containing only the elements that are common to both input arrays.

For Older Browsers:

If working with older browsers that do not support arrow functions or includes, the following code can be used:

var filteredArray = array1.filter(function(n) {
    return array2.indexOf(n) !== -1;
});

Cautions:

It's important to note that both includes and indexOf perform comparisons using strict equality (===). If the arrays contain objects, only the object references are compared. To accommodate custom comparison logic, employ Array.prototype.some instead.

The above is the detailed content of How Can I Find the Intersection of Two JavaScript Arrays Without Using External Libraries?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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