In Javascript, how do I check if an array has duplicate values?(在 Javascript 中,如何检查数组是否有重复值?)
问题描述
可能重复:
在 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 中,如何检查数组是否有重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Javascript 中,如何检查数组是否有重复值?


基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01