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

How to Find the Intersection of Two Arrays in JavaScript Without Using Libraries?

Patricia Arquette
Release: 2025-01-02 15:11:40
Original
526 people have browsed it

How to Find the Intersection of Two Arrays in JavaScript Without Using Libraries?

Finding Array Intersections Without Libraries

Seeking a simplified solution to compute the intersection of arrays in JavaScript? This article explores a code snippet that delivers this functionality without relying on external libraries.

Question:

How can we write code that takes two arrays as input and returns the elements that appear in both arrays?

Answer:

Harnessing the power of the filter method, we can create a concise solution to this problem:

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

This code filters the first array, returning only the elements that are also found in the second array.

Implementation:

The filter method iterates over each element in the array and returns a new array containing only the elements that pass the provided condition. In our case, the condition checks if the current element is included in the second array using the includes method.

Additional Notes:

For older browsers that do not support arrow functions or includes:

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

Remember, both includes and indexOf use strict equality for comparisons. If your arrays contain objects, the code will compare object references rather than their content. Consider using Array.prototype.some for custom comparison logic.

The above is the detailed content of How to Find the Intersection of Two Arrays in JavaScript Without Using Libraries?. 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