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
Release: 2025-01-01 08:07:10
Original
914 people have browsed it

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

If targeting older browsers that lack the "includes" method and arrow functions:

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

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!

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