在 Javascript 中,如何检查数组是否有重复值?
可能的重复:
在 JavaScript 数组中查找重复值的最简单方法
如何检查数组是否有重复值?
如果数组中的某些元素相同,则返回 true。否则,返回 false。
['hello','goodbye','hey'] //return false because no duplicates exist
['hello','goodbye','hello'] // return true because duplicates exist
请注意,我不关心查找重复项,只想要布尔结果数组是否包含重复项。
Possible Duplicate:
Easiest way to find duplicate values in a javascript array
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.
['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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
为什么使用这种方法:
我认为这是处理多个数组和循环时最好的方法,这个例子非常简单,但在某些情况下,例如迭代多个循环并迭代对象时,是最可靠和最佳的方法。
说明:
在这个例子中,数组被迭代,element与array[i]相同,i是循环当前所在数组的位置,然后函数检查读取数组中的位置初始化为空,如果该元素不在读取数组中,它将返回-1,并且将被推送到读取数组,否则它将返回其位置并且不会被推送,一旦所有元素数组已被迭代,读取的数组将被打印到控制台
Why use this method:
I think this is the best way to do it when dealing with multiple arrays and loops, this exaple is very simple but in some cases such when iterating with several loops and iterating through objects this is the most reliable and optimal way to do it.
Explanation:
In this example the array is iterated, element is the same as array[i] i being the position of the array that the loop is currently on, then the function checks the position in the read array which is initialized as empty, if the element is not in the read array it'll return -1 and it'll be pushed to the read array, else it'll return its position and won't be pushed, once all the element of array has been iterated the read array will be printed to console
使用
Set
的解决方案的一个好处是查找列表中现有项目的O(1)
性能,而不必循环遍历它。使用
Some
的解决方案的一个好处是,当尽早发现重复项时会发生短路,因此当条件已满足时,您不必继续评估数组的其余部分。将两者结合起来的一种解决方案是增量构建一个集合,如果集合中存在当前元素,则提前终止,否则添加它并继续处理下一个元素。
根据JSBench.me,对于各种用例来说应该表现得很好。设置大小方法在没有重复的情况下是最快的,而检查 some + indexOf 在非常早期的重复中是最快的,但是这个解决方案在这两种情况下都表现良好,使其成为一个很好的全面实现。
One nice thing about solutions that use
Set
isO(1)
performance on looking up existing items in a list, rather than having to loop back over it.One nice thing about solutions that use
Some
is short-circuiting when the duplicate is found early, so you don't have to continue evaluating the rest of the array when the condition is already met.One solution that combines both is to incrementally build a set, early terminate if the current element exists in the set, otherwise add it and move on to the next element.
According to JSBench.me, should preform pretty well for the varried use cases. The set size approach is fastest with no dupes, and checking some + indexOf is fatest with a very early dupe, but this solution performs well in both scenarios, making it a good all-around implementation.
在上面的代码中,我采用了一个数组,并在触发特定函数(onExamSelect)时,我们检查重复项并推送唯一元素。
In the above code, I have taken an array and on triggering a particular function (onExamSelect) we are checking duplicates and pushing unique elements.
到 2023 年,这是对对象数组执行此操作的最佳方法,检查严格相等性。
Set
无法做到这一点。In 2023, this is the best way to do it for an array of objects, checking strict equality. A
Set
cannot do this.ES6 的单线解决方案
One line solutions with ES6
您可以使用 SET 删除重复项并进行比较,如果将数组复制到集合中,它将删除所有重复项。然后简单地将数组的长度与集合的大小进行比较。
You could use SET to remove duplicates and compare, If you copy the array into a set it will remove any duplicates. Then simply compare the length of the array to the size of the set.
另一种方法(也适用于数组中的对象/数组元素1)可能是2:
另请参阅...
1 需要支持 JSON 的浏览器,或一个 JSON 库 如果没有。
2 edit: 函数现在可用于简单检查或返回重复值数组
Another approach (also for object/array elements within the array1) could be2:
See also...
1 needs a browser that supports JSON, or a JSON library if not.
2 edit: function can now be used for simple check or to return an array of duplicate values
您可以利用
indexOf
和lastIndexOf
。如果两个索引不相同,则有重复。You can take benefit of
indexOf
andlastIndexOf
. if both indexes are not same, you have duplicate.如果要处理简单值,则可以使用
array.some()
和indexof()
例如,让我们说
vals
is[“ b”,“ a”,“ a”,“ c”]
如果任何任何表达式返回true,则会返回true。在这里,我们将迭代值(从索引0),然后调用索引(),该索引将返回给定项目的第一次出现的索引(或在数组中不在数字中)。如果它的ID较小,则在当前的ID之前必须至少有一个相同的值。因此,迭代3将返回true,因为“ a”(在索引2)首先在索引1上找到。
If you are dealing with simple values, you can use
array.some()
andindexOf()
for example let's say
vals
is["b", "a", "a", "c"]
some()
will return true if any expression returns true. Here we'll iterate values (from the index 0) and call the indexOf() that will return the index of the first occurrence of given item (or -1 if not in the array). If its id is smaller that the current one, there must be at least one same value before it. thus iteration 3 will return true as "a" (at index 2) is first found at index 1.很简单,你可以使用 Array.prototype.every 函数
is just simple, you can use the
Array.prototype.every
function如果您有 ES2015 环境(截至撰写本文时:io.js、IE11、Chrome、Firefox、WebKit nightly),那么以下内容将起作用,并且速度会很快(即 O(n)):
如果您只需要字符串数组中的值,以下内容将起作用:
我们使用“哈希表”
valuesSoFar
,其键是迄今为止我们在数组中看到的值。我们使用in
进行查找,看看该值是否已经被发现;如果是这样,我们跳出循环并返回true
。如果您需要一个不仅仅适用于字符串值的函数,那么以下函数也可以,但性能不高;它是 O(n2) 而不是 O(n)。
区别在于,我们使用数组而不是
valuesSoFar
的哈希表,因为 JavaScript“哈希表”(即对象)只有字符串键。这意味着我们失去了in
的 O(1) 查找时间,而是获得了indexOf
的 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)):
If you only need string values in the array, the following will work:
We use a "hash table"
valuesSoFar
whose keys are the values we've seen in the array so far. We do a lookup usingin
to see if that value has been spotted already; if so, we bail out of the loop and returntrue
.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).
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 ofin
, instead getting an O(n) lookup time ofindexOf
.