在 Javascript 中,如何检查数组是否具有重复值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7376598/
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 02:01:55  来源:igfitidea点击:

In Javascript, how do I check if an array has duplicate values?

javascriptduplicates

提问by user847495

Possible Duplicate:
Easiest way to find duplicate values in a javascript array

可能的重复:
在 javascript 数组中查找重复值的最简单方法

How do I check if an array has duplicate values?

如何检查数组是否具有重复值?

If some elements in the array are the same, then return true. Otherwise, return false.

如果数组中的某些元素相同,则返回 true。否则,返回false。

['hello','goodbye','hey'] //return false because no duplicates exist
['hello','goodbye','hello'] // return true because duplicates exist

Notice I don't care about finding the duplication, only want Boolean result whether arrays contains duplications.

注意我不关心找到重复项,只想要布尔结果是否数组包含重复项。

回答by Domenic

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

如果您有 ES2015 环境(在撰写本文时:io.js、IE11、Chrome、Firefox、WebKit nightly),那么以下将起作用,并且速度会很快(即 O(n)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}


If you only need string values in the array, the following will work:

如果您只需要数组中的字符串值,以下将起作用:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

We use a "hash table" valuesSoFarwhose keys are the values we've seen in the array so far. We do a lookup using into see if that value has been spotted already; if so, we bail out of the loop and return true.

我们使用一个“哈希表”,valuesSoFar其键是我们目前在数组中看到的值。我们使用查找in该值是否已经被发现;如果是这样,我们退出循环并返回true



If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

如果您需要一个不仅仅适用于字符串值的函数,下面的方法也可以使用,但性能不佳;它是 O(n 2) 而不是 O(n)。

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

不同之处只是我们使用数组而不是哈希表 for valuesSoFar,因为 JavaScript 的“哈希表”(即对象)只有字符串键。这意味着我们失去了 O(1) 的查找时间in,而是获得了 O(n) 的查找时间indexOf

回答by KooiInc

Another approach (also for object/array elements within the array1) could be2:

另一种方法(也适用于数组1 中的对象/数组元素)可能是2

function chkDuplicates(arr,justCheck){
  var len = arr.length, tmp = {}, arrtmp = arr.slice(), dupes = [];
  arrtmp.sort();
  while(len--){
   var val = arrtmp[len];
   if (/nul|nan|infini/i.test(String(val))){
     val = String(val);
    }
    if (tmp[JSON.stringify(val)]){
       if (justCheck) {return true;}
       dupes.push(val);
    }
    tmp[JSON.stringify(val)] = true;
  }
  return justCheck ? false : dupes.length ? dupes : null;
}
//usages
chkDuplicates([1,2,3,4,5],true);                           //=> false
chkDuplicates([1,2,3,4,5,9,10,5,1,2],true);                //=> true
chkDuplicates([{a:1,b:2},1,2,3,4,{a:1,b:2},[1,2,3]],true); //=> true
chkDuplicates([null,1,2,3,4,{a:1,b:2},NaN],true);          //=> false
chkDuplicates([1,2,3,4,5,1,2]);                            //=> [1,2]
chkDuplicates([1,2,3,4,5]);                                //=> null

See also...

也可以看看...

1needs a browser that supports JSON, or a JSON libraryif not.
2edit:function can now be used for simple check or to return an array of duplicate values

1需要一个支持 JSON 的浏览器,如果不支持,则需要一个JSON 库
2编辑:函数现在可用于简单检查或返回重复值数组

回答by tushar747

Well I did a bit of searching around the internet for you and I found this handy link.

好吧,我为您在互联网上进行了一些搜索,并找到了这个方便的链接。

Easiest way to find duplicate values in a JavaScript array

在 JavaScript 数组中查找重复值的最简单方法

You can adapt the sample code that is provided in the above link, courtesy of "swilliams" to your solution.

您可以将上面链接中提供的示例代码(由“swilliams”提供给您的解决方案)改编。