A, the Set

1. Overview:

  • ES6 provides a new data structure, Set, similar to an array, but with unique values and no duplicates. That is, a Set is a Set of values that are not repeated

  • There is no key name, there is only a key value, or the key name and the key value are the same value, the two values are always equal

  • Takes an array as an argument to initialize

const set = new Set([1.2.3.4.4]);
consle.log(set);/ / [1, 2, 3, 4]
console.log([...set]);/ / [1, 2, 3, 4]
Copy the code

2. Properties and methods

Operation method:

  • .add() adds a value and returns the Set structure itself

  • .delete() deletes a value and returns a Boolean value indicating whether the deletion was successful

  • .has() returns a Boolean value indicating whether the value is a member of Set

  • .clear() clears all members with no return value

Traversal method:

  • .keys() returns the key name
  • .values() returns the key value

.values() and.keys() behave the same way because Set has no key name but only key value, or because the key name and key value are the same value

Instances of the Set structure are traversable by default, so the. Values method can be omitted.

let set = new Set(["red"."green"."blue"]);
for (let i of set.keys()) {
  console.log("set.keys:", i);
}

let set2 = new Set(["red"."green"."blue"]);
for (let i of set2.values()) {
  console.log("set.values:", i);
}

let set4 = new Set(["red"."green"."blue"]);
for (let i of set4) {
   console.log("Instances of the Set structure are traversable by default:", i);
}
Copy the code
  • .entries() returns key value pairs
  • .forEach( )

3, How to convert a Set to an Array

The array. from method converts a Set structure to an Array

4. Usage Scenarios:

(1) Remove duplicate members of the array

1 / / instance
const set = new Set([1.2.3.4.4]);
console.log(set);/ / [1, 2, 3, 4]

2 / / instance
const items = new Set([1.2.3.4.4.5.6.6]);
const array = Array.from(items);/ / [6]

3 / / instance
function unique(array){
   // Check if it is an array
  if(! (arrinstanceof Array)) {
    console.log("It's not an array.");
    return
  } else {
     return Array.from(new Set(array));The array. from method converts a Set structure to an Array
  }
}

unique([1.1.2.3]);/ / [1, 2, 3]
unique('111');// It is not an array
Copy the code

Note: The Set method only applies to ordinary arrays such as [1, 2, 3, 4, 4]. It does not apply to arrays containing objects such as [{a: 1}, {a: 1}, {a: 2}].

(2) Remove repeated characters from the string

const str = "ascddsdfg";
const DEPLICATE_STR = new Set(str);
console.log([...DEPLICATE_STR].join(' '));//ascdfg
Copy the code

Join () converts all the elements in the array to a string;

(3) Find the union/intersection/difference set

The map and filter methods of arrays can be used indirectly on sets, which do not have map and filter methods

let a = new Set([1.2.3]);
let b = new Set([4.3.2]);

let union = [...new Set([...a, ...b])];
console.log("And set =", union); / / [1, 2, 3, 4]

let intersect = [...new Set([...a].filter((x) = > b.has(x)))];
console.log("Intersection =", intersect); / / [2, 3]

let difference = Array.from(new Set([...a].filter((x) = >! b.has(x))));console.log("Difference set =", difference); / / [1]
Copy the code

5, the difference between WeakSet and Set:

Difference between WeakSet and Set:

  • Is a collection of non-repeatable values

  • Members can only be objects

  • No size property, not traversal

Use:

WeakSet is useful for storing DOM nodes without worrying about memory leaks when they are removed from documents.

Second, the Map

1, an overview of the

  • It’s essentially a set of key pairs, like a set;

  • Traditional key-value pairs are limited by string-to-value mappings, so the Map structure provides value-to-value mappings.

  • You can traverse, you can convert to any data format

  • It takes an array of key-value pairs.

  • Both sets and maps can generate new maps;

  • Only references to the same object are treated as the same key by the Map structure;

The Map key is actually bound to the memory address, and as long as the memory address is different, it is treated as two keys.

const map = new Map(a); map.set(['aaa'.5]);
console.log(map.get(['aaa']));//undefined

// Only references to the same object are treated as references to the same key; So you have to point to the same object, save it as an object;
const map = new Map(a);const k1 = ['aaa'];
map.set(k1,5);
console.log(map.get(k1));/ / 5
Copy the code

2. Properties and methods

Operation method:

  • .set( )

  • .get( )

  • .delete( )

  • .has( )

  • .clear( )

Traversal method:

  • .keys() returns a traverser for the key name

  • .values() returns a traverser for key values

  • .entries() returns a traverser for all members

  • ForEach () traverses all members of the Map

The order in which a Map is traversed is the order in which it is inserted

3. Interconversion with other data structures

(1) Map to array: use the extension operator

(2) Array to Map

(3) Map to Object: object.create ()

(4) Object to Map: object.entries ()

(5) Map to JSON

(6) Convert JSON to Map

//1, Map to array
const map0 = new Map().set(1.'a').set(2.'b');
console.log(":",[...map0]);//[{1,'a'},{2,b}]
console.log("Map to array:",[...map0].keys());/ / [1, 2]
console.log("Map to array:",[...map0].values());//['a','b']

//2, pass the array directly to the Map constructor
new Map([[true.7],
[{foo:3},Const map1 = new Map().set(1,'a').set(2,'b'); function strMapToObj(strMap){ let obj = Object.create(null); For (let [k,v] of strMap){obj[k] = v; for(let [k] of strMap){obj[k] = v; } return obj } strMapToObj(map1); // const obj1 = {1:'a', 2:b'} let map2 = new Map(object.entries (obj))// object.entries () returns an array of key-value pairs for the given Object's own enumerable properties [['1', 'a'], ['2', 'b']]
 
Copy the code

4. Usage Scenarios:

You can use the map and filter methods of arrays; maps themselves do not have map and filter methods

(1) Realize Map filtering and traversal

const map0 = new Map().set(1,'a).set(2,'b).set(3,'c');

const map1 = new Map([...map0].filter(([k,v])=>k < 3));
const map2 = new Map([...map0].map(([k,v])=>[k*2,'_'+v])) 
Copy the code

5. Difference between WeakMap and Map

  • Accept only objects as key names (except null);
  • WeakMap key name refers to the object, is weak reference, that is, will not be included in the garbage collection mechanism;

(That is to say, once it is no longer needed, the key name object and corresponding key value pair in WeakMap will disappear automatically, without manual deletion)

(Note: the weak reference is only the key name, not the key value, which is still a normal reference.)

  • Special occasions of WeakMap:

  • The object that its key corresponds to may disappear in the future.

  • The WeakMap structure helps prevent memory leaks.

Differences in API:

  • No traversal, i.e. no keys(), values(), entries() methods, and no size property;

  • Cannot be emptied, that is, clear() method is not supported, so WeakMap only has set(), GET (), HAS (), delete() methods;

Learning Materials:

ECMAScript 6 Getting Started -Set and Map data structures