SoFunction
Updated on 2025-03-03

Detailed explanation of the usage methods of set collection and map collection in ES6 and source code examples

Set and map understanding

Newly added in ES6, set set and map set are data storage structures (before ES6, the data storage structure was only array and object). Different scenarios use different sets to store data.

set collection

The Set object allows you to store unique values ​​of any type, whether they are original values ​​or object references.

Set collection syntax:

//Create a set collection and pass the argument into an iterable objectconst s1 = new Set(iterable);

API

name type Introduction
() Prototype method Add data
() Prototype method Determine whether there is a data
() Prototype method Delete data
() Prototype method Clear the collection
property property Collection length
for of Prototype method Traversal

Set source code example:

// () Add data to the created collection    const s1 = new Set();
    (1)
    (2)
    (3)
    (4)
    (1) //Invalid addition because the data is duplicated    (s1)

// () Determine whether the data exists    ((1))
    ((10))

// () Return whether the deletion is successful    (1)
    (s1)
    ((10))

// () Clear the collection    ()
    (s1)

// Properties can only be read, not modified    ()

// 6.Travel: for of, because it is an iterable object    for(const item of s1){
        (item)
    }
    // Rewrite instance method forEach    ((item, index, s) => {
        // index is not a subscript, the set collection has no subscript        // The value of the first parameter in forEach is the same and the value of the second parameter, both representing each item of data in set        (item, index, s)
    })

Use scenarios

//Deduplication of array  const arr = [1,1,22,22,3,1,88,88,65,123,444,65];
  const s = new Set(arr);
  ([...s]);

//Or it will be done in one sentence  const result = [...new Set(arr)];
  (result);//[1,22,3,88,65,123,444,65]

// The intersection, union, difference of two arrays, and the result is a new array  const arr1 = [12,34,55,33,11,33,5,12];
  const arr2 = [55,34,11,78,10,19,88,88,99,99];

// Complete with set// Intersection: You have array elements that I have, and form a new array  const cross = [...new Set(arr1)].filter(item => (item) >= 0);
  (cross);//[]

// Unity: New array after combining and deduplication  const result = [...new Set([...arr1,...arr2])];
  (result);

// Difference set: You have and I don't, I have array elements that you don't. Make up a new array  let arr4 = (item=>{
      // judging the data that exists in arr1 and does not exist in arr2 and data that does not exist in arr1 and does not exist in arr2      return (item) && !(item) || !(item) && (item)
  })
  (arr4)  //[12, 33, 5, 78, 10, 19, 88, 99]

Map collection (map)

Map object saves key-value pairs. Any value (object or original value) can be used as a key or as a value.

Map collection syntax:

let swk=new Map()
(swk);//Map(0)

API

name type Introduction
(key,value) Prototype method Add data
(key) Prototype method Get data
(key) Prototype method Determine whether there is a data
(key) Prototype method Delete data
() Prototype method Clear the collection
property Prototype method Collection length
for of Prototype method Traversal

Map collection source code example:

        let swk=new Map();
         (swk);      

    // 1. Add map element        // (key,value) Set the key-value pair of Map object (key name, key value) Return to the current object        ('uname', 'Sun Wukong');
        ('age', 600);
        ('master', 'Tang Monk');
        ('weapon', 'Golden Cudgel');
        (swk); //Map(4) {'uname' => 'Sun Wukong', 'age' => 600, 'master' => 'Tang Monk', 'weapon' => 'Golden Cudgel'}        ('age', 601);
        (swk);
        // If the key does not exist, add an item        // If the key exists, modify it
   // 2. Get map element        // (key) Returns the value corresponding to the key value. If the key does not exist, it returns undefined        (('uname')); //Sun Wukong        (({})); //undefined

   // 3. Determine whether the element exists has Return a boolean value        (('uname')); //true
        (({})); //false

  // 4. Delete the map element        ('weapon');
        (swk); //Map(3) {'uname' => 'Sun Wukong', 'age' => 600, 'master' => 'Tang Monk'}
  //5. Clear the map elements        // ();
        // (swk); //Map(0) {size: 0}

  // 6. Map element length        (); //3

  // 7. You can use the for of loop        for (let [key, value] of swk) {
            (key, value);
            for (let item in value) {
                (value[item])
            }
        }

        ('=====forEach=====');


  // 8. You can use forEach to traverse        ((item, index, map) => {
            (index); //uname age master
            ('==========');
            (item); // Sun Wukong 60 Monk Tang            ('==========');
            (map);
            ('==========');
        })

The difference between Maps and Objects

  • A key of an Object can only be a string or Symbols, but a key of a Map can be any value (string, for the next, function, NaN).
  • Key values ​​in Map are ordered, while keys added to objects are not.
  • The number of key-value pairs of Map can be obtained from the size property, while the number of key-value pairs of Object can only be calculated manually.
  • Objects all have their own prototypes, and the key names on the prototype chain may conflict with the key names you set on the object.

This article mainly explains the set collection in javascript ES6, detailed explanation of the usage methods of map collections and source code examples. For more information about javascript ES6, please see the related links below