Skip to content
Advertisement

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

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.

Similar question:

Advertisement

Answer

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):

JavaScript

In case, if you are to return as a function for duplicates. This is for similar type of case.

Reference: https://stackoverflow.com/a/57532964/8119511

Advertisement