How to create a list of unique items in JavaScript?

后端 未结 8 455
半阙折子戏
半阙折子戏 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:08

    I find the other answers to be rather complicated for no gain that I can see.

    We can use the indexOf method of the Array to verify if an item exists in it before pushing:

    const duplicated_values = ['one', 'one', 'one', 'one', 'two', 'three', 'three', 'four'];
    const unique_list = [];
    
    duplicated_values.forEach(value => {
      if (unique_list.indexOf(value) === -1) {
        unique_list.push(value);
      }
    });
    
    console.log(unique_list);

    That will work with any type of variable as well, even objects (given the identifier actually reference the same entity, merely equivalent objects are not seen as the same).

提交回复
热议问题