問題描述
可能重復:
在 javascript 數組中查找重復值的最簡單方法一個>
如何檢查數組是否有重復值?
How do I check if an array has duplicate values?
如果數組中的某些元素相同,則返回true.否則,返回 false.
If some elements in the array are the same, then return true. Otherwise, return 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.
推薦答案
如果你有一個 ES2015 環境(在寫這篇文章時:io.js, IE11, Chrome, Firefox, WebKit nightly),那么下面的將起作用,并且會很快(即 O(n)):
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)):
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;
}
我們使用哈希表"valuesSoFar
,其鍵是我們目前在數組中看到的值.我們使用 in
進行查找以查看是否已經發現了該值;如果是這樣,我們跳出循環并返回 true
.
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
.
如果您需要的函數不僅僅適用于字符串值,則以下方法可以使用,但性能不佳;它是 O(n2) 而不是 O(n).
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).
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;
}
不同之處在于我們對 valuesSoFar
使用數組而不是哈希表,因為 JavaScript 哈希表"(即對象)只有字符串鍵.這意味著我們失去了 in
的 O(1) 查找時間,而獲得了 indexOf
的 O(n) 查找時間.
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
.
這篇關于在 Javascript 中,如何檢查數組是否有重復值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!