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

时间:2022-05-28 21:23:21

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

3 个解决方案

#1


106  

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),那么以下内容将会起作用,并且速度很快(即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" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to 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(n2)而不是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.

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

#2


2  

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

另一种方法(也适用于array1中的对象/数组元素)可以是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...

也可以看看...

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

1需要支持JSON的浏览器,否则需要JSON库。 2编辑:现在可以使用函数进行简单检查或返回重复值数组

#3


-2  

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”提供给您的解决方案。

#1


106  

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),那么以下内容将会起作用,并且速度很快(即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" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to 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(n2)而不是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.

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

#2


2  

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

另一种方法(也适用于array1中的对象/数组元素)可以是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...

也可以看看...

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

1需要支持JSON的浏览器,否则需要JSON库。 2编辑:现在可以使用函数进行简单检查或返回重复值数组

#3


-2  

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”提供给您的解决方案。