I need to check a JavaScript array to see if there are any duplicate values. What's the easiest way to do this? I just need to find what the duplicated values are - I don't actually need their indexes or how many times they are duplicated.
I know I can loop through the array and check all the other values for a match, but it seems like there should be an easier way. Any ideas? Thanks!
ES6 offers the Set data structure which is basically an array that doesn't accept duplicates. With the Set data structure, there's a very easy way to find duplicates in an array (using only one loop).
Here's my code
With ES6 (or using Babel or Typescipt) you can simply do:
https://es6console.com/j58euhbt/
You could sort the array and then run through it and then see if the next (or previous) index is the same as the current. Assuming your sort algorithm is good, this should be less than O(n2):
ES5 only (i.e., it needs a filter() polyfill for IE8 and below):
Modifying @RaphaelMontanaro's solution, borrowing from @Nosredna's blog, here is what you could do if you just want to identify the duplicate elements from your array.
Thanks for the elegant solution, @Nosredna!
If you want to elimate the duplicates, try this great solution:
Source: http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/