如何在 JavaScript 中创建唯一项目列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11688692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:44:42  来源:igfitidea点击:

How to create a list of unique items in JavaScript?

javascriptarrayscouchdb

提问by Ronny

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

在我的 CouchDB 缩减功能中,我需要将项目列表缩减为唯一的项目。

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

注意:在这种情况下,可以有一个列表,它将是少数字符串类型的项目。

My current way is to set keys of a object, then return the keys of that object since the place the code can't use things like _.uniqfor example.

我目前的方法是设置一个对象的键,然后返回该对象的键,因为代码不能使用_.uniq例如这样的东西。

I'd like to find a more elegant way to spell it than this.

我想找到一种比这更优雅的拼写方式。

function(keys, values, rereduce) {
  // values is a Array of Arrays
  values = Array.concat.apply(null, values);
  var uniq = {};
  values.forEach(function(item) { uniq[item] = true; });
  return Object.keys(uniq);
}

回答by Eugene Naydenov

Commonly, the approach you used is a good idea. But I could propose a solution that will make the algorithm a lot faster.

通常,您使用的方法是一个好主意。但我可以提出一个解决方案,使算法更快。

function unique(arr) {
    var u = {}, a = [];
    for(var i = 0, l = arr.length; i < l; ++i){
        if(!u.hasOwnProperty(arr[i])) {
            a.push(arr[i]);
            u[arr[i]] = 1;
        }
    }
    return a;
}

As you can see we have only one loop here.

正如你所看到的,我们这里只有一个循环。

I've made an examplethat is testing both your and my solutions. Try to play with it.

我做了一个例子来测试你和我的解决方案。试着玩它。

回答by Joakim Poromaa Helger

The best method seem to be using ES6 and Set. Single line and faster* than above according to fiddle

最好的方法似乎是使用 ES6 和 Set。根据小提琴,单行并且比上面更快*

    
const myList = [1,4,5,1,2,4,5,6,7];
const unique = [...new Set(myList)];
    
console.log(unique);

*tested in safari

*在 safari 中测试

回答by Rob Hague

An alternative that's suitable for small lists would be to ape the Unix command line approach of sort | uniq:

适用于小列表的另一种方法是模仿 Unix 命令行方法sort | uniq

    function unique(a) {
        return a.sort().filter(function(value, index, array) {
            return (index === 0) || (value !== array[index-1]);
        });
    }

This function sorts the argument, and then filters the result to omit any items that are equal to their predecessor.

此函数对参数进行排序,然后过滤结果以省略与其前任相等的任何项目。

The keys-based approach is fine, and will have better performance characteristics for large numbers of items (O(n) for inserting n items into a hashtable, compared to O(n log n) for sorting the array). However, this is unlikely to be noticeable on small lists. Moreover, with this version you could modify it to use a different sorting or equality function if necessary; with hash keys you're stuck with JavaScripts notion of key equality.

基于键的方法很好,并且对于大量项目具有更好的性能特征(与用于对数组排序的 O(n log n) 相比,用于将 n 个项目插入哈希表的 O(n))。然而,这在小名单上不太可能引起注意。此外,在此版本中,您可以根据需要修改它以使用不同的排序或相等函数;使用散列键,你会被 JavaScript 的键相等概念所困扰。

回答by Alexander Mills

This should work with anything, not just strings:

这应该适用于任何东西,而不仅仅是字符串:

export const getUniqueList =  (a: Array<any>) : Array<any> => {

  const set = new Set<any>();

  for(let v of a){
      set.add(v);
  }

  return Array.from(set);

};

the above can just be reduced to:

以上可以简化为:

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

:)

:)

回答by rwblackburn

This is an old question, I know. However, it is at the top of some google searches, so I wanted to add that you can combine the answers from @RobHague and @EugeneNaydenov using the following:

这是一个老问题,我知道。但是,它位于某些 google 搜索的顶部,所以我想补充一点,您可以使用以下内容组合来自 @RobHague 和 @EugeneNaydenov 的答案:

function unique(arr) {
  const u = {};
  return arr.filter((v) => {
    return u[v] = !u.hasOwnProperty(v);
  });
};

You can also ignore undefinedvalues (often handy) by adding:

您还可以通过添加以下内容来忽略未定义的值(通常很方便):

function unique(arr) {
  const u = {};
  return arr.filter((v) => {
    return u[v] = (v !== undefined && !u.hasOwnProperty(v));
  });
};

You can play with this solution here: https://jsfiddle.net/s8d14v5n/

您可以在此处使用此解决方案:https: //jsfiddle.net/s8d14v5n/

回答by JW Buitenhuis

Using Object.keys will give you strings if you put in integer arguments (uniq([1,2,3]) => ['1','2','3']. Here's one with Array.reduce:

如果您输入整数参数 (uniq([1,2,3]) => ['1','2','3'],则使用 Object.keys 将为您提供字符串。这是 Array.reduce 的一个:

function uniq(list) {
    return list.reduce((acc, d) => acc.includes(d) ? acc : acc.concat(d), []);
}

回答by Suche Ganbaatar

what about

关于什么

    function unique(list) {
      for (i = 0; i<list.length; i++) {
        for (j=i+1; j<list.length; j++) {
          if (list[i] == list[j]) {
            list.splice(j, 1);
          }
        }
      }
    }