“This is the 27th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”

ECMAScript 6’s new Set is a new collection type that brings collection data structures to the language. Sets are in many ways like enhanced maps because most of their apis and behaviors are common

Use the new keyword and the Set constructor to create an empty collection:

const m = new Set();

If you want to initialize the instance while creating it, you can pass an iterable to the Set constructor that contains the elements to be inserted into the new collection instance:

// Initialize the collection with an array
const s1 = new Set(["val1"."val2"."val3"]);
alert(s1.size); / / 3

// Initialize the collection with a custom iterator
const s2 = new Set({[Symbol.iterator]: function* () {
yield "val1";
yield "val2";
yield "val3"; }}); alert(s2.size);/ / 3
Copy the code

A Set is used to store a unique value of any type, be it a primitive type or an object reference.

  • Can only save values without key names
  • Strict type detection such as string numbers not equal numeric numbers
  • The value is unique
  • The traversal order is the order of addition to save the callback function

Basic API

After initialization, you can add values using add(), query with has(), get the number of elements by size, and delete elements using delete() and clear() :

const s = new Set(a); alert(s.has("Matt")); // false
alert(s.size); / / 0

s.add("Matt")
 .add("Frisbie");
alert(s.has("Matt")); // true
alert(s.size); / / 2

s.delete("Matt");
alert(s.has("Matt")); // false
alert(s.has("Frisbie")); // true
alert(s.size); / / 1

s.clear(); // Destroy all values in the collection instance
alert(s.has("Matt")); // false
alert(s.has("Frisbie")); // false
alert(s.size); / / 0
Copy the code

Add () returns an instance of the collection, so multiple add operations can be concatenated, including initialization:

const s = new Set().add("val1");
s.add("val2")
 .add("val3");
alert(s.size); / / 3
Copy the code

Notice that the attributes of the object are eventually converted to strings

let obj = { 1: "qdxx"."1": "xiaoyiya" };
console.table(obj); //{1:" small also "}
Copy the code

So when you use an object as a key, you convert the object to a string

let obj = { 1: "qdxx"."1": "xiaoyiya" };
    console.table(obj);   // {1:" small also "}

let hd = { [obj]: "Little too." };
    console.table(hd);      //{[object object]: ""}

console.log(hd[obj.toString()]);   / / small also
console.log(hd["[object Object]"]); / / small also
Copy the code

Like a Map, a Set can contain any JavaScript data type as a value. Collections also use the SameValueZero operation (defined internally by ECMAScript and not available in the language), which is basically equivalent to using strict object equality criteria to check for value matching, i.e., Set is strictly type-constrained, and the value 1 below belongs to two different values than the string 1

let set = new Set(a); set.add(1);
set.add("1");
console.log(set); //Set(2) {1, "1"}
Copy the code

Some good usage scenarios

An array of conversion

You can use the dot syntax or array. form static method to convert a Set type to an Array, which allows you to use Array handlers

const set = new Set(["qdxx"."xiaoyiya"]);
console.log([...set]); //["qdxx", "xiaoyiya"]
console.log(Array.from(set)); //["qdxx", "xiaoyiya"]
Copy the code

Removes values greater than 5 from the Set

let hd = new Set("123456789");
hd = new Set([...hd].filter(item= > item < 5));
console.log(hd);
Copy the code

Remove duplicate

Removing string duplicates

console.log([...new Set("xiaoyiya")].join(""));//xiaoy
Copy the code

Removing array duplicates

const arr = [1.2.3.5.2.3];
console.log(... newSet(arr)); / / 1,2,4,5
Copy the code

Through the data

Keys ()/values()/entries() can all be used to return iterated objects (at this point we should see many similarities and differences between Map and Set), keys and values result in the same result because Set only has values.

const hd = new Set(["qdxx"."xiaoyiya"]);
console.log(hd.values()); //SetIterator {"qdxx", "xiaoyiya"}
console.log(hd.keys()); //SetIterator {"qdxx", "xiaoyiya"}
console.log(hd.entries()); //SetIterator {"qdxx" => "qdxx", "xiaoyiya" => "xiaoyiya"}
Copy the code

You can use forEach to iterate through Set data, with the values method being used to create iterators by default.

Value and key are the same in order to maintain consistency with the traversal arguments.

let arr = [7.6.2.8.2.6];
let set = new Set(arr);
// Use forEach to traverse
set.forEach((item,key) = > console.log(item,key));
Copy the code

You can also iterate through Set data using the for of method, creating iterators using the values method by default

// Use for/of to traverse
let set = new Set([7.6.2.8.2.6]);

for (const iterator of set) {
	console.log(iterator);
}
Copy the code

intersection

Gets the elements that are common to both collections

let hd = new Set(['qdxx'.'xiaoyiya']);
let cms = new Set(['Front-end learning'.'qdxx']);
let newSet = new Set(
	[...hd].filter(item= > cms.has(item))
);
console.log(newSet); //{"qdxx"}
Copy the code

Difference set

Occurs in set A but not in set B

let hd = new Set(['qdxx'.'xiaoyiya']);
let cms = new Set(['Front-end learning'.'qdxx']);
let newSet = new Set(
	[...hd].filter(item= >! cms.has(item)) );console.log(newSet); //{"xiaoyiya"}
Copy the code

And set

Combining two sets into a new Set certainly does not produce duplicate elements due to the Set property.

et hd = new Set(['qdxx'.'xiaoyiya']);
let cms = new Set(['Front-end learning'.'qdxx']);
let newSet = new Set([...hd, ...cms]);
console.log(newSet); // [" QDXX ","xiaoyiya"," front-end learning "]
Copy the code