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

How Can I Efficiently Find the Intersection, Difference, and Symmetric Difference of Two JavaScript Arrays?

Barbara Streisand
Release: 2024-12-29 03:39:10
Original
860 people have browsed it

How Can I Efficiently Find the Intersection, Difference, and Symmetric Difference of Two JavaScript Arrays?

Finding Array Differences in JavaScript: Intersection, Difference, and Symmetric Difference

In JavaScript, comparing arrays element-by-element can be tedious. To simplify this process, let's explore a powerful tool: Array.prototype.includes().

Intersection

To obtain the values that are common to both arrays, we can use filter(). For instance:

let intersection = arr1.filter(x => arr2.includes(x));
Copy after login

This produces the intersection: [2, 3].

Difference

To identify values present only in arr1, we can filter out the elements that exist in arr2.

let difference = arr1.filter(x => !arr2.includes(x));
Copy after login

This results in the difference: [1].

Symmetric Difference

To get the elements found exclusively in either arr1 or arr2, we combine the two differences:

let symDifference = arr1.filter(x => !arr2.includes(x))
                        .concat(arr2.filter(x => !arr1.includes(x)));
Copy after login

This produces the symmetric difference: [1].

As highlighted by @Joshaven Potter, these methods can be added directly to the Array.prototype for enhanced flexibility:

Array.prototype.diff = function(arr2) { 
  return this.filter(x => !arr2.includes(x)); 
}
Copy after login

Then, you can use it directly on arrays:

[1, 2, 3].diff([2, 3]) // [1]
Copy after login

The above is the detailed content of How Can I Efficiently Find the Intersection, Difference, and Symmetric Difference of Two JavaScript Arrays?. For more information, please follow other related articles on the PHP Chinese website!

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