Basic usage of ES6 Set in js

ES6 provides a new data structure Set. It is similar to an array, but the values ​​of the members are unique and there are no duplicate values.

const s =new Set();
 
[2,3,5,4,5,2,2].forEach(x => s.add(x));
// Set structures do not add duplicate values
 
for(let i of s) {
  console.log(i);
}
 
// Initialization
// Example 1 can accept an array as a parameter
const set =new Set([1,2,3,4,4,]);
 
// ... Converting an array to a comma-separated sequence of parameters
console.log([...set]);
 
// Example 2
const items =new Set([1,2,3,4,5,5,5,5,]);
console.log(items.size);
 
 
// Example 3 can accept other data structures with iterable interface as parameters
const set2 =new Set(document.querySelectorAll('div'));
console.log(set.size);
 
// Similar to
const set2 =new Set();
document
    .querySelectorAll('div')
    .forEach(div => set.add(div));
console.log(set.size);
 
// NaN in set is equal to itself, the rest of the comparison is equivalent to ===
let set3 =new Set();
let a = NaN;
let b = NaN;
set3.add(a);
set3.add(b);
console.log(set3)
 
// Two objects are always not equal
let set4 =new Set();
set4.add({}); // 1
console.log(set4.size);
 
set4.add({}); // 2
console.log(set4.size);
let set =new Set(['red','green','blue']);
 
// Return key name
for(let item of set.keys()) {
  console.log(item);
}
 
// Return key value
for(let item of set.values()) {
  console.log(item);
}
// set key name=key value
 
// Return key-value pairs
for(let item of set.entries()){
  console.log(item);
}
 
// You can directly traverse Set with for of
// The difference between for in and for of is that in is an iterative object, of is an iterative value
for (let x of set) {
  console.log(x);
}
 
// set also has a forEach() method
set.forEach((value, key) => console.log(key +' : ' + value));
// The argument of the forEach method here is a handler function.
 
// The map and filter methods for arrays can also be used indirectly for Set
let s =new Set([1,2,3]);
 
// map maps the original array to a new array
s =new Set([...s].map(x => x * 2));
console.log(s);
 
// filter returns a new array after filtering
s =new Set([...s].filter(x => (x % 3) ==0));
console.log(s);
 
// Implement merge, intersection and difference sets
let a =new Set([1,2,3]);
let b =new Set([4,3,2]);
 
let union =new Set([...a, ...b]);
console.log(union);
 
let intersect =new Set([...a].filter(x => b.has(x)));
console.log(intersect);
 
let difference =new Set([...a].filter(x => !b.has(x)));
console.log(difference);
 
// Two workarounds for synchronizing changes to the original Set structure during traversal operations
 
// 1. Use the original Set structure to map a new structure, and then assign a value to the original Set structure
let set1 =new Set([1,2,3]);
set1 =new Set([...set1].map(val => val *2));
console.log(set1);
 
// 2. Using Array.from
let set2 =new Set([1,2,3]);
set2 =new Set(Array.from(set2, val => val * 2));
console.log(set2);

Leave a Reply