How to create a list of unique items in JavaScript?

后端 未结 8 412
半阙折子戏
半阙折子戏 2020-12-09 11:54

In my CouchDB reduce function I need to reduce a list of items to the unique ones.

Note: In that case it\'s ok to have a list, it will be a small number of items

8条回答
  •  有刺的猬
    2020-12-09 12:16

    This should work with anything, not just strings:

    export const getUniqueList =  (a: Array) : Array => {
    
      const set = new Set();
    
      for(let v of a){
          set.add(v);
      }
    
      return Array.from(set);
    
    };
    

    the above can just be reduced to:

    export const getUniqueValues = (a: Array) => {
       return Array.from(new Set(a));
    };
    

    :)

提交回复
热议问题