Home > Web Front-end > JS Tutorial > What's the Simplest JavaScript Code for Finding Array Intersections?

What's the Simplest JavaScript Code for Finding Array Intersections?

Mary-Kate Olsen
Release: 2024-12-19 16:54:10
Original
548 people have browsed it

What's the Simplest JavaScript Code for Finding Array Intersections?

Simplest Code for Array Intersection in Javascript

Array intersections are a common operation in programming, where you want to find the elements that exist in both arrays. In Javascript, a library-free implementation can be achieved using the following approaches:

Firstly, leverage a combination of Array.prototype.filter and Array.prototype.includes:

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

For older browsers, you can utilize Array.prototype.indexOf and a non-arrow function instead:

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

It's important to note that both .includes and .indexOf utilize === for element comparison. Therefore, when dealing with arrays containing objects, only object references are compared. If you require custom comparison logic, consider using Array.prototype.some instead.

The above is the detailed content of What's the Simplest JavaScript Code for Finding Array Intersections?. 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