• Breaking News

    JavaScript Set Objects - Tips and Tricks

    Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.

    The Set object lets you store unique values of any type, whether primitive values or object references.

    You can use Set objects instead of logical operators (like OR) or as a counterpart of array methods like include().




    Here you have a couple of useful use cases:

    Using JavaScript Set and the has() method instead of a logical operator like "OR"

    You can replace an endless OR operation like this one:

    function match(skill) {* filter elements*/
        if (skill === 'javascript' || skill === 'react' || skill === 'vue') { // I'm running out of space here
            console.log('match found');
        } else {
            console.log('no match');
        }
    }
    By using a much better and "readable" code like the following:

    function matchBetter(skill) {
        const code = ['javascript', 'java', 'react', 'vue', 'php', 'cobol'];
        const setOfSkills = new Set(code);
    
        if (setOfSkills.has(skill)) {
            console.log('match found'); 
        } else {
            console.log('no match');
        }
    }
    And now, just run both codes:

    
    match('react'); // match found!
    
    matchBetter('react'); //match found!
    
    

    Opposite of "includes()" logic using the Set object and its delete() method 

    Let's suppose that based on a given member, you want to find its counterpart.

    We can achieve this goal easily using Set's "delete()" method, as follows:

    function findCounterPart(member) {
            const members = ['mary','tom'] ;
            const setMembers = new Set(members) ;
    
            setMembers.delete(member) ;
            var result = setMembers.values().next().value ;
    
    
            console.log('result: ' + result);
    }
    And the expected results are:

    
    findCounterPart('mary');  // tom
    
    findCounterPart('tom'); // mary
    
    
    


    JavaScript SET reference here: MDN Web Docs


    No comments