{b.push(i);})let u=Array.from(new Set(b));"; 3. Use set object and concat(), the syntax "Array.from(new Set (a.concat(b)))”."/> {b.push(i);})let u=Array.from(new Set(b));"; 3. Use set object and concat(), the syntax "Array.from(new Set (a.concat(b)))”.">
Home >Web Front-end >Front-end Q&A >How to find the union of es6 arrays
3 methods: 1. Use set object and expansion operator, syntax "Array.from(new Set([...a,...b]))"; 2. Use set object and Traversal statement, syntax "a.forEach(i=>{b.push(i);})let u=Array.from(new Set(b));"; 3. Use set object and concat(), syntax "Array.from(new Set(a.concat(b)))".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
3 ways to find the union of es6 arrays
Method 1: Use the set object and the spread operator "... ”
Use the spread operator “...” to merge two arrays
Use the set object to remove duplicates
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.
Example:
let a=[1, 2, 3]; let b=[3, 5, 2]; console.log(a); console.log(b); // 并集 let unionSet = Array.from(new Set([...a, ...b])); console.log("并集:"); console.log(unionSet);
Method 2: Using set objects and traversal statements
Use forEach() and push() to merge two arrays
Use forEach() to traverse the a array, and use push() to add the elements of the a array to the end of the b array one by one.
Use the set object to remove duplicates
Example:
let a=[1, 2, 3]; let b=[3, 5, 2]; console.log(a); console.log(b); a.forEach(item => { b.push(item); }) // 并集 let unionSet = Array.from(new Set(b)); console.log("并集:"); console.log(unionSet);
##Method 3: Using set objects and concat()
The concat() method is used to connect two or more arrays.array1.concat(array2,array3,...,arrayX)will return a new array. The array is generated by adding all arrayX parameters to arrayObject. If the argument to concat() is an array, the elements in the array are added, not the array. Example:
let a=[1, 2, 3]; let b=[2, 4, 6]; console.log(a); console.log(b); // 并集 let unionSet = Array.from(new Set(a.concat(b))); console.log("并集:"); console.log(unionSet);[Related recommendations:
javascript video tutorial, web front-end]
The above is the detailed content of How to find the union of es6 arrays. For more information, please follow other related articles on the PHP Chinese website!