Home > Web Front-end > JS Tutorial > How Can I Find the Difference Between Two Arrays in JavaScript?

How Can I Find the Difference Between Two Arrays in JavaScript?

Barbara Streisand
Release: 2024-12-20 02:39:16
Original
248 people have browsed it

How Can I Find the Difference Between Two Arrays in JavaScript?

Determining the Difference between Two Arrays in JavaScript

Introduction:

Determining the difference between two arrays is a common task in JavaScript. The difference can be defined as the elements that are present in one array but not in the other. This article provides several approaches to achieve this using JavaScript's built-in methods.

Intersection and Difference:

One approach is to use the Array.prototype.includes() method. It can be employed for both finding the intersection (common elements) and the difference between two arrays.

Intersection:

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

This filter produces an array containing the elements that are common to both arr1 and arr2.

Difference:

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

This filter creates an array with the elements that are present only in arr1, not in arr2.

Symmetric Difference:

Additionally, one may desire to determine the "exclusive or" (symmetric difference) between two arrays, which consists of unique elements from both arrays. This can be obtained by combining the difference of both arrays:

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

Enhancement:

For improved usability, it is possible to define a custom method for Array.prototype that allows for direct usage on arrays:

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

With this enhancement, one can easily determine the difference:

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

The above is the detailed content of How Can I Find the Difference Between Two Arrays in JavaScript?. 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