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!
using underscore.js
Here is a very light and easy way:
Here is mine simple and one line solution.
It searches not unique elements first, then makes found array unique with the use of Set.
So we have array of duplicates in the end.
Fast and elegant way using es6 object destructuring and reduce
It runs in O(n) (1 iteration over the array) and doesn't repeat values that appear more than 2 times
This is my answer from the duplicate thread (!):
Got tired of seeing all bad examples with for-loops or jQuery. Javascript has the perfect tools for this nowadays: sort, map and reduce.
Find duplicate items
More functional syntax:
@Dmytro-Laptin pointed out some code code be removed. This is a more compact version of the same code. Using some ES6 tricks and higher order functions:
Using Function.prototype.bind:
Find unique values from 3 arrays (or more):
Just a polyfill for array indexOf for old browsers:
jQuery solution using "inArray":
ES2015
instead of adding the 'Array.prototype.indexOf'