How to add an array of values to a Set

前端 未结 9 642
轮回少年
轮回少年 2020-12-29 02:15

The old school way of adding all values of an array into the Set is:

// for the sake of this example imagine this set was created somewhere else 
// and I ca         


        
相关标签:
9条回答
  • 2020-12-29 02:42

    You can also use Array.reduce():

    const mySet = new Set();
    mySet.add(42); // Just to illustrate that an existing Set is used
    
    [1, 2, 3].reduce((s, e) => s.add(e), mySet);
    
    0 讨论(0)
  • 2020-12-29 02:44

    This is IMO the most elegant

    // for a new Set 
    const x = new Set([1,2,3,4]);
    
    // for an existing Set
    const y = new Set();
    
    [1,2,3,4].forEach(y.add, y);
    
    0 讨论(0)
  • 2020-12-29 02:48

    How about using the spread operator to easily blend your new array items into an existing set?

    const mySet = new Set([1,2,3,4])
    const additionalSet = [5,6,7,8,9]
    mySet = new Set([...mySet, ...additionalSet])
    

    JSFIDDLE

    0 讨论(0)
提交回复
热议问题