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.
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);
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);
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)));
[Related recommendations :javascript video tutorial、web 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!