Learn about collections and dictionaries in front end applications

This is the 20th day of my participation in the More text Challenge. For more details, see more text Challenge

In the context of the changing front end, ES6 has basically covered the universal popularity. Data structure sets and dictionaries are also used in ES6 syntax. ES6 implements the idea of collections and dictionaries by using the Set and Map functions. How can collections and dictionaries be used flexibly?

In this article, we’ll walk you through how collections and dictionaries are used in front ends, and how maps and sets are used to implement some common scenarios in front ends. Let’s learn ~πŸ™‹β™€οΈ

1. πŸ“ collection

1. What is a set?

  • A set is an unordered and unique data structure;
  • ES6I have a set calledSet οΌ›
  • Set of common operations: to determine whether an element is in the set, intersection……

2. Front end and Set: Use the Set in ES6

What can a Set do in ES6?

  • useSetObject:new 、 add 、 delete 、 has 、 size
  • The iterationSet: Multiple iteration methods,Set 与 ArrayMutual transformation, seek union/intersection/difference set

3. Use Set to simulate union, intersection, and difference sets

(1) Simulation of union operation

We can create a function that returns a new set containing all the elements in setA and setB. Iterate over the two sets and add all elements to the set of the union. The following code looks like this:

// Simulate the union operation
constUnion = (setAe, setB) => {const unionab = new Set()
    setA.forEach(value= > unionab.add(value))
    setB.forEach(value= > unionab.add(value))
    return [...unionab]
}

console.log(union([1.2.5.8.9], [4.5.8.9.10])) //[1, 2, 5, 8,9, 4, 10]
Copy the code

(2) Simulation of intersection operation

Simulating the intersection operation requires the creation of a helper function that generates a new set containing elements shared by both setA and setB sets. The specific code is as follows:

// Simulate the intersection operation
const intersection = (setA, setB) = > {
    const intersectionSet = new Set(a)const arrSetB = new Set(setB)
    setA.forEach(value= > {
        if (arrSetB.has(value)) {
            intersectionSet.add(value)
        }
    })
    return [...intersectionSet]
}

console.log(intersection([1.2.5.8.9], [4.5.8.9.10])) / /,8,9 [5]
Copy the code

(3) Simulation difference set operation

A difference collection creates elements that setA does have and setB does not. In short, it’s setA minus the part that intersects setB, and the rest is the part of the difference set.

// Simulate difference set operation
const difference = (setA, setB) = > {
    const differenceSet = new Set(a)const arrSetB = new Set(setB)
    setA.forEach(value= > {
        if(! arrSetB.has(value)) { differenceSet.add(value) } })return [...differenceSet]
}

console.log(difference([1.2.5.8.9], [4.5.8.9.10])) / / [1, 2]
Copy the code

4. Use extension operators to simulate union, intersection, and difference sets

Above we implemented a Set to simulate union, intersection, and difference sets, but this seems a little redundant and sounds friendly if we have to execute so many lines of code at a time when we have a lot of data.

So, we’ve introduced a new approach to ES6’s extension operators.

If you use the extension operator, the whole process takes only three steps:

  • Convert a collection to an array;
  • Perform the required operations;
  • Convert the result back to the set.

We then use the extension operators to implement the union, intersection, and difference sets.

(1) Implement the union with the extension operator

Look at the following code:

// Simulate the union operation
const union = (setA, setB) = > {
    return new Set([...setA, ...setB]);
}
console.log(union([1.2.5.8.9], [4.5.8.9.10])) //[1, 2, 5, 8,9, 4, 10]
Copy the code

As you can see from the above code, using the extension operator, you can implement the concrete union operation in just one line of code, which looks much cleaner.

So we’re going to continue to implement the intersection and the difference set in this way.

(2) Use the extension operator to achieve the intersection

// Simulate the intersection operation
const intersection = (setA, setB) = > {
    const arrB = new Set(setB);
    return [...new Set([...setA].filter(x= > arrB.has(x)))]
}
console.log(intersection([1.2.5.8.9], [4.5.8.9.10])) / / [5, 8, 9]
Copy the code

With the same effect as the union, using the extension operator, it is very simple to implement the function of intersection.

(3) Use the extended operator to implement the difference set

// Simulate difference set operation
const difference = (setA, setB) = > {
    const arrB = new Set(setB)
    return [...new Set([...setA].filter(x= >! arrB.has(x)))] }console.log(difference([1.2.5.8.9], [4.5.8.9.10])) / / [1, 2]
Copy the code

Again, use the extended operator approach, but as opposed to the intersection, which filters out the elements that setB has, and the difference set, which filters out the elements setB does not have, to achieve a concrete effect.

5. Leetcode Case analysis

(1) The intersection of two arrays of LeetCode349

1) the question

Here is a link to the original question

Given two arrays, write a function to calculate their intersection.

Examples of input and output:

  • Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
  • Output: [9, 4]
  • explain:
    • nums1 ε’Œ nums2The intersection of the two arrays is [9, 4].

2

  • Find intersection and unordered unique.
  • Use collections.

3) Steps to solve the problem

  • With the collection to thenums1duplicate removal
  • traversenums1,nums2Is also contained in.

4) Code implementation

/ * * *@param {Array} Nums1 array 1 *@param {Array} Nums2 array 2 *@returns * /
let intersection = function(nums1, nums2){

    // Deduplicate the array first
    const arr1 = new Set(nums1);
    const arr2 = new Set(nums2);
    
    // Filter out elements that arR1 already has in ARR2, and the filter result is the intersection
    // Has can be changed to includes
    const arr3 = [...arr1].filter(item= > arr2.has(item));

    return arr3;
}
console.log(intersection([1.2.3.4], [4.6.8]))
Copy the code

2. πŸ“‚ dictionary

1. What is a dictionary?

  • A dictionary is similar to a set. A dictionary is also a data structure that stores unique values, but it is stored as key-value pairs.
  • Note: dictionaries must be stored as key-value pairs!!

2. Front end and collections: Use Map in ES6

What can MAPS do in ES6?

  • useMapObject:new 、 set 、 delete 、 clear οΌ›
  • Dictionary common operations, key-value pair to add, delete, modify and check.

3. Use the Map API

Here is some code to show the MAP API.

const map = new Map(a)/ / to add
map.set('monday'.'Monday')
map.set('Tuesday'.'Tuesday')
map.set('Wednesday'.'Wednesday')

console.log(map.has('monday')) //true
console.log(map.size) / / 3
console.log(map.keys()) // Output {' Monday ', 'Tuesday', 'Wednesday'}
console.log(map.values()) // Output {' Monday ', 'Tuesday ',' Wednesday '}
console.log(map.get('monday')) / / Monday

/ / delete
map.delete('monday')

/ / to empty
map.clear()

/ / change
map.set('monday'.'Thursday')

Copy the code

4. Leetcode Case analysis

(1) The intersection of two arrays of LeetCode349

1) the question

Here is a link to the original question

Given two arrays, write a function to calculate their intersection.

Examples of input and output:

  • Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
  • Output: [9, 4]
  • explain:
    • nums1 ε’Œ nums2The intersection of the two arrays is [9, 4].

2

  • onums1 ε’Œ nums2There are values.
  • withThe dictionarySet up a mapping relationship and recordnums1There are values in.
  • traversenums2To find out thenums1There are also values in.

3) Steps to solve the problem

  • Create a newThe dictionaryTo traverse thenums1Fill in theThe dictionary.
  • traversenums2, the value encountered in the dictionary is selected and removed from the dictionary.

4) Code implementation

/ * * *@param {Array} Nums1 array 1 *@param {Array} Nums2 array 2 *@returns * /
let intersection = function(nums1, nums2){
    // Create a dictionary first
    const map = new Map(a);// Go through each nums1 and put it into an array
    nums1.forEach(n= > {
        map.set(n, true);
    });

    const res = [];
    // Traverse each nums2
    nums2.forEach(n= > {
        // Compare with nums1, push res if same
        if(map.get(n)){ res.push(n); map.delete(n); }});return res;
}

console.log(intersection([1.2.2.1], [2.2]))
Copy the code

(2) LeetCode20 effectively parentheses

1) the question

Here is a link to the original question

Given a only include a ‘(‘,’) ‘, ‘{‘,’} ‘, ‘/’, ‘ ‘the string s, determine whether a string is effective.

Examples of input and output:

  • Input: s = “()[]{}”
  • Output: true,
  • explain:
    • Open and close parentheses correspond to open and close.

2) How to solve the problem

  • Check whether the number of strings is even, if not, return directly.
  • Create a dictionary and map each of the three brackets into it.
  • Walk through the string.
  • traversenums1,nums2Is also contained in.

3) Code implementation

/ * * * *@param {String} S parenthesis string *@returns boolean* /
 let isValid = function(s){
    if(s.length % 2= = =1) {return false;
    }

    const stack = [];
    const map = new Map(a); map.set('('.') ');
    map.set('{'.'} ');
    map.set('['.'] ');

    for(let i = 0; i < s.length; i++){
        const c = s[i];
        if(map.has(c)){
            stack.push(c);
        }else{
            // Get the value of the last parenthesis in the stack
            const t = stack[stack.length - 1];
            if(map.get(t) === c){
                stack.pop();
            }else{
                return false; }}}return stack.length === 0;
}

console.log(isValid('[]')) //true
console.log(isValid('(]')) //false
console.log(isValid('(/)')) //false

Copy the code

(3) Leetcode1 the sum of two numbers

1) the question

Here is a link to the original question

Given an integer array nums and an integer target, find the two integers in the array whose sum is target and return their array indices.

You can assume that there is only one answer for each input. However, the same element in the array must not appear repeatedly in the answer.

You can return the answers in any order.

Examples of input and output:

  • Nums = [2,7,11,15], target = 9
  • Output: [0, 1]
  • explain:
    • becausenums[0] + nums[1] == 9To return to[0, 1] 。

2

  • thenumsImagine being an intimate;
  • thetargetThink of it as a matching condition;
  • Use a dictionary to set up a dating agency that stores the numbers and subscripts of your partners.

3) Steps to solve the problem

  • Create a new dictionary as a dating agency;
  • numsValue, one by one to introduce the object, there is no appropriate on the first registration, there is a suitable hand success;
  • Key value pairs, keykeyRepresents the value of this object, valuevalueRepresents the contact information of the object, that is, the subscript.

4) Code implementation

/ * * * *@param {Array} * nums array@param {Number} Target Indicates the target and *@returns [] * /
let twoSum = function(nums, target){
    const map = new Map(a);for(i = 0; i < nums.length; i++){
        // The value of the person who came to find the object
        const n = nums[i];
        // The value of the target object you want to find
        const n2 = target - n;
        // When the object is found
        if(map.has(n2)){
            return [map.get(n2), i];
        }
        // If the object is not found, put it in the dictionary and wait for it to arrive
        else{ map.set(n, i); }}return 'No target match';
}

console.log(twoSum([1.2.3.4].6)) / / [1, 3]
Copy the code

(4) LeetCode3 the most important string without duplicate characters

1) the question

Here is a link to the original question

Given a string, find the longest string that does not contain repeating characters.

Examples of input and output:

  • Input: s = “abcabCBb”

  • Output: 3

  • Explanation:

    • Because the most common string with no duplicate characters is"abc", so its length is zero3 。
  • 2

    • First find all substrings that do not contain repeating characters.
    • Find the substring with the largest length and return its length.

    3) Steps to solve the problem

    • Maintain a sliding window with double Pointers for clipping substrings.
    • Keep moving the right pointer, and when you encounter a repeating character, move the left pointer to the next bit of the repeating character.
    • Record the length of all Windows and return the maximum value.

4) Code implementation

/ * * *@param {string} s
 * @return {number}* /
let lengthOfLongestSubstring = function(s){
    let l = 0;
    let res = 0;
    const map = new Map(a);for(let r = 0; r < s.length; r++){
        // map.get(r) >= l Ensure that the subscript is to the right of the left pointer
        if(map.has(s[r]) && map.get(s[r]) >= l){
            l = map.get(s[r]) + 1;
        }
        res = Math.max(res, r - l + 1);
        map.set(s[r], r);
    }
    return res;
}

console.log(lengthOfLongestSubstring('ssdfsf')) / / 3
Copy the code

(5) LeetCode76 minimum overwrite substring

1) the question

Here is a link to the original question

I give you a string s and a string T. Returns the smallest string in s that covers all characters in t. Returns the empty string “” if there is no substring in s that covers all characters of T.

** Note: ** If such a substring exists in s, we guarantee that it is the only answer.

Examples of input and output:

  • Type: s = “ADOBECODEBANC”, t = “ABC”
  • Output: “BANC”
  • explain:
    • BANCcoverABCThree letters, and it’sThe boy string.

2

  • Let’s find out all the containsTThe substring.
  • Find the substring with the smallest length and return it.

3) Steps to solve the problem

  • Maintain a sliding window with double Pointers.
  • Move the right pointer to containTAnd move the left pointer to minimize inclusionTThe length of the substring of.

4) Code implementation

/ * * *@param {string} s
 * @param {string} t
 * @return {string}* /
let minWindow = function(s, t){
    // Maintain a sliding window with double Pointers
    // The pointer starts at the first position, that is, the index is 0
    let l = 0;
    let r = 0;
    // Create a dictionary to indicate the number of characters needed for the substring
    const need = new Map(a);for(let c of t){
        // Iterate over the characters of the substring and store them in the dictionary
        need.set(c, need.has(c) ? need.get(c) + 1 : 1);
    }

    // Number of required types
    let needType = need.size;
    let res = ' ';
    // Move the right pointer
    while(r < s.length){
        // As the right pointer moves, we keep getting the current character
        const c = s[r];
        // Determine if the current character is in our requirement list
        if(need.has(c)){
            need.set(c, need.get(c) - 1);
            if (need.get(c) === 0){
                needType -= 1; }}while(needType === 0) {// Prints the sliding window and its representation substring
            // The substring method follows the principle of closing left and opening right
            // console.log(s.substring(l, r + 1));
            const newRes = s.substring(l, r + 1);
            // Find the smallest substring
            if(! res || newRes.length < res.length){ res = newRes; }C2 represents the current character of the left pointer
            const c2 = s[l];
            // If the left pointer is in the list of requirements
            if(need.has(c2)){
                // The number of characters required needs to be increased
                need.set(c2, need.get(c2) + 1);
                // If the required number of characters is 1, then this character is required again
                if (need.get(c2) === 1){
                    needType += 1;
                }
            }
            l += 1;
        }// When we break out of the while loop, it means that the left pointer can no longer move, and we need to start moving the right pointer
        // If the right pointer moves, increments by 1
        r += 1;
    }
    return res;
}

console.log(minWindow('ASDFFGFGCX'.'AFG')) // ASDFFG
Copy the code

Third, πŸ“† conclusion

Dictionaries and collections are required questions for front end interviews, and are used relatively frequently in daily development, so it is important to master the contents of dictionaries and collections.

So much for the use of dictionaries and collections in the front end! Hope to be helpful to everyone!

  • Pay attention to the public number Monday research office, the first time to pay attention to learning dry goods, more wonderful columns to unlock for you ~
  • If this article is useful to you, remember to click three to go
  • Accidentally bumped into each other, see you next time! πŸ₯‚ πŸ₯‚ πŸ₯‚