Home > Web Front-end > JS Tutorial > How Can I Find the Unique Elements in One JavaScript Array That Are Not Present in Another?

How Can I Find the Unique Elements in One JavaScript Array That Are Not Present in Another?

DDD
Release: 2024-12-29 20:41:14
Original
269 people have browsed it

How Can I Find the Unique Elements in One JavaScript Array That Are Not Present in Another?

Getting the Difference Between Two Arrays in JavaScript

Determining the difference between two arrays in JavaScript is a common requirement. This refers to identifying the elements that exist uniquely in one array but not in the other.

Using ES2016/ES7 Array.prototype.includes()

To achieve this, we can employ Array.prototype.includes(), introduced in ES2016/ES7. This method enables us to determine if an array contains a specific value.

Method to Get Difference

To calculate the difference between two arrays, where 'a1' and 'a2' are the input arrays, we can use the following code:

let difference = a1.filter(x => !a2.includes(x));
Copy after login

Explanation

The difference represents the values present only in 'a1' and not in 'a2'. The filter() method iterates over 'a1' and returns a new array containing elements that satisfy the given condition. The condition "!a2.includes(x)" checks if an element 'x' is not present in 'a2'. Thus, the resulting array 'difference' contains the elements of 'a1' that are absent in 'a2'.

Example

Consider the following example:

var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];

let difference = a1.filter(x => !a2.includes(x));
console.log(difference); // Output: ["c", "d"]
Copy after login

In this example, 'difference' will contain the elements "c" and "d", representing the values present in 'a2' but not in 'a1'.

The above is the detailed content of How Can I Find the Unique Elements in One JavaScript Array That Are Not Present in Another?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template