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

How to Find the Difference Between Two Arrays in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 18:21:13580browse

How to Find the Difference Between Two Arrays in JavaScript?

Finding the Difference Between Arrays in JavaScript

Comparing and manipulating arrays is a common task in programming. In JavaScript, one useful operation is the ability to determine the difference between two arrays.

Using Array.prototype.includes()

Array.prototype.includes() is a powerful tool introduced in ES2016 (ES7) that allows you to check if a value exists within an array. Using this method, you can filter out elements in one array that are present in another.

Determining the Intersection

The intersection of two arrays consists of elements that are common to both. To obtain the intersection, use the following code:

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

Calculating the Difference

The difference between two arrays (values present in one array but not the other) can be calculated using the following code:

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

Determining the Symmetric Difference

The symmetric difference includes elements that are unique to either array, but not both. It can be computed using the following code:

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

Custom Array Prototype Method

As an alternative, you can extend the Array prototype to add a diff() method that performs the difference operation:

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

Usage:

[1, 2, 3].diff([2, 3]) // [1]

The above is the detailed content of How to Find the Difference Between Two Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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