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

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

Susan Sarandon
Susan SarandonOriginal
2025-01-01 08:07:10920browse

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

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!

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