How to find the intersection of two arrays in es6

青灯夜游
Release: 2022-04-19 19:04:49
Original
3985 people have browsed it

Implementation method: 1. Use the "new Set (array)" statement to convert both arrays into set collection types; 2. Use "new Set([...set 1].filter(x = > Set 2.has(x)))" statement can be used to obtain the intersection of two sets, and a new set containing all intersection elements will be returned.

How to find the intersection of two arrays in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In es6, you can use the has() method of the set object in conjunction with the filter() of the array to find the intersection of two arrays.

  • Set is a new data structure provided by ES6, which is similar to an array, but has no duplicate values. Using this feature, we can convert the array to a Set type for deduplication, and then use the Array.from method to convert it to an array again.

  • The Set has() method indicates whether the Set object contains the specified value. Returns true if the specified value exists, false otherwise.

let a=[1, 2, 3];
let b=[3, 5, 2];
newA = new Set(a);
newB = new Set(b); 
let intersectionSet = new Set([...newA].filter(x => newB.has(x)));
console.log(intersectionSet);
Copy after login

How to find the intersection of two arrays in es6

It can be seen that at this time, the intersection elements are included in a set collection and returned. The Array.from method can be used to convert the set into an array. Type

  • Array.from method is used to convert two types of objects into real arrays: array-like objects and iterable objects (including ES6 New data structures Set and Map).

let intersectionSet = Array.from(new Set([...newA].filter(x => newB.has(x))));
console.log(intersectionSet);
Copy after login

How to find the intersection of two arrays in es6

Expand knowledge: finding union/difference set

let a = new Set([1, 2, 3]);
let b = new Set([3, 5, 2]); 

// 并集
let unionSet = new Set([...a, ...b]);
//[1,2,3,5]

// ab差集
let differenceABSet = new Set([...a].filter(x => !b.has(x)));
Copy after login

[Related recommendations :javascript video tutorialweb front-end

The above is the detailed content of How to find the intersection of two arrays in es6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
es6
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