Javascript Set的应用

Javascript Set的应用

Set 是一组独特的项,即没有重复元素。ES6中的Set有序:集合的元素可以按照插入顺序进行迭代。Set可以存储任何类型的值,无论是原始类型还是对象。

Javascript中Set的应用:

  • 从数组中删除重复元素
  • 从两个数组的唯一值创建一个唯一的数组
  • 两个集合的并集
  • 两个集合的交集

方法1:从数组中删除重复元素

在这种方法中,我们有一个包含多个重复值的集合,我们将从集合中删除重复项。

例子:

Javascript

// Create an array containing duplicate items
const duplcateArray = [
    2, 3, 4, 8, 8, 9, 9, 4, 2, 
    3, 3, 4, 6, 7, 5, 32, 3, 4, 5
];
 
// Use Set and Spread Operator to remove 
// duplicate items from an array
console.log([...new Set(duplcateArray)]);

输出:

[ 2, 3, 4,  8, 9, 6, 7, 5, 32 ]  

方法2:从两个数组的唯一值创建唯一数组

在这个方法中,我们将从两个数组的唯一值创建一个唯一数组。

示例:

Javascript

// Declare first array
const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
// Declare second array
const arr2 = [7, 8, 9, 10, 6, 11, 12, 13];
 
// Function to get the unique values array
// from two arrays
function uniqueArray(arr1, arr2) {
    const set = new Set(arr1.concat(arr2));
    return Array.from(set);
}
 
// Display the array containing
// unique values
console.log(uniqueArray(arr1, arr2));

输出

[
   1, 2, 3,  4,  5,  6,
   7, 8, 9, 10, 11, 12,
  13
]

方法3:两个集合的并集

在这种方法中,我们将连接两个集合的值

示例:

Javascript

// Create first set
let a = new Set([1, 2, 3]);
 
// Create second set
let b = new Set([4, 3, 2]);
 
// Use spread Operation to Merge both
// set and then use Set() constructor
// to get union of both set
let union = new Set([...a, ...b]);
 
// Display the result
console.log(union)

输出:

{ 1, 2, 3, 4 }  

方法4:两个集合的交集

在这种方法中,我们将获得两个集合的交集。

示例:

Javascript

// Create first set
let a = new Set([1, 2, 3]);
 
// Create second set
let b = new Set([4, 3, 2]);
 
// Get the instersection of both set
let intersection = new Set(
    [...a].filter(x => b.has(x)));
 
// Display the result
console.log(intersection)

输出

Set(2) { 2, 3 }

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程