This is the fourth day of my participation in the August More Text Challenge. For details, see “August More Text Challenge”.

Continuing from above, today’s collection and dictionary introduction.

A collection of

  • An unordered and unique data structure.

  • In ES6 we have a Set, the name Set.

  • Set of common operations: to determine whether an element is in the set, intersection, and so on…

duplicate removal

const arr = [1.1.2.2.3.3]
const arr2 = [...new Set(arr)]

console.log(arr2)
/ / [1, 2, 3]
Copy the code

Determines whether the element is in the set

const set = new Set(arr)
const has = set.has(2)

console.log(has)
// true
Copy the code

masked

const set = new Set([1.2])
const set2 = new Set([2.3])

const set3 = [...set].filter(item => set2.has(item))

console.log(set3)
/ / [2]

Copy the code

O difference set

const set = new Set([1.2])
const set2 = new Set([2.3])

const set3 = [...set].filter(item => ! set2.has(item))

console.log(set3)
/ / [1]

Copy the code

Set Basic Operations

  • Use Set objects: new, add, DELETE, has, size

  • Iterative Set: multiple iterative methods, Set and Array transformation, intersection/difference Set

  • Iterate over the key of the Set

const mySet = new Set([1.2.3.4.5])

for (let key of mySet) console.log(key);

// 1, 2, 3, 4, 5
Copy the code
  • The iterationSetvalue
const mySet = new Set([1.2.3.4.5])

for (let key of mySet.values) console.log(key);

// 1, 2, 3, 4, 5
Copy the code
  • The iterationSetThe key and the value
const mySet = new Set([1.2.3.4.5])

for (let [key, value] of mySet.entries()) 

console.log(key, value);

// 1 1 2 2 3 3 4 4 5 5
Copy the code

We can see that the Set’s key and value are the same.

  • Turn the Set Array
const mySet = new Set([1.2.3.4.5])

const myArr = [...mySet]

const myArr2 = Array.from(mySet)

Copy the code

The dictionary

  • Like a collection, a dictionary is a data structure that stores unique values, but in the form of key-value pairs.

  • In ES6 we have the collection, the name Map.

  • Common operations in dictionaries: adding, deleting, modifying and querying key-value pairs.

Set basic operations

const map = new Map()
/ / to add
map.set(' You ', 'ok ')/ / delete
map.deleteThe map (' you ').clear(a)/ / to empty
/ / change
map.set(' You ', 'no good ')/ / check
map.get(' you ')Copy the code

The time complexity is order one.

masked

function intersection(nums1: number[], nums2: number[]): number[] {
    const map = new Map()
    nums1.forEach(e => {
        map.set(e, true)
    })
    const res = []
    nums2.forEach(e => {
        if(map.get(e)) {
            res.push(e)
            map.delete(e)
        }
    })
    return res
};
Copy the code

That’s all for today, see you tomorrow!