1. What is Set()
Set is a new data structure in es6 , similar to an array , but one of its characteristics is that all elements are unique and there are no repeated values. We generally call it a set.
Set itself is a constructor used to generate the Set data structure
2. Method of adding, deleting, modifying and checking
2.1 Add element add
Add a value and return the Set structure itself. When adding elements that already exist in the instance, the set will not process the addition
let list=new Set();
list.add(1)
list.add(2).add(3).add(3) // 2只被添加了一次
2.2 delete element delete
Delete a value and return a Boolean value indicating whether the deletion was successful
let list=new Set([1,20,30,40])
list.delete(30) //删除值为30的元素,这里的30并非下标
2.3 Determine whether an element exists has
Returns a Boolean value to determine whether the value is a member of Set
let list=new Set([1,2,3,4])
list.has(2)//true
12
2.4 Clear all elements clear
Clear all members, no return value
let list=new Set([1,2,3,4])
list.clear()
12
3. Traversal method
3.1 traverse keys()
Returns the traverser of the key name, which is equivalent to returning the key value traverser values()
let list2=new Set(['a','b','c'])
for(let key of list2.keys()){
console.log(key)//a,b,c
}
1234
3.2 traverse values()
Returns an iterator for key values
let list=new Set(['a','b','c'])
for(let value of list.values()){
console.log(value)//a,b,c
}
1234
3.3 Traversing entries()
Returns an iterator for key-value pairs
let list=new Set(['4','5','hello'])
for (let item of list.entries()) {
console.log(item);
}
// ['4','4'] ['5','5'] ['hello','hello']
12345
3.4 Traversing forEach()
Use the callback function to iterate over each member
let list=new Set(['4','5','hello'])
list.forEach((value, key) => console.log(key + ' : ' + value))
// 4:4 5:5 hello:hello
123
4. Usage
4.1 for array deduplication
let arr =[3,5,2,2,5,5];
let setArr =newSet(arr)// 返回set数据结构 Set(3) {3, 5, 2}//方法一 es6的...解构
let unique1 =[...setArr ];//去重转数组后 [3,5,2]//方法二 Array.from()解析类数组为数组
let unique2 = Array.from(setArr )//去重转数组后 [3,5,2]12345678
4.2 for string deduplication
let str ="352255";
let unique =[...newSet(str)].join("");// 352 12
4.3 Realize union, intersection, and difference
let a =newSet([1,2,3]);
let b =newSet([4,3,2]);// 并集
let union=newSet([...a,...b]);// Set {1, 2, 3, 4}// 交集
let intersect =newSet([...a].filter(x => b.has(x)));// set {2, 3}// (a 相对于 b 的)差集
let difference =newSet([...a].filter(x =>!b.has(x)));// Set {1}