This post will discuss how to find all duplicates in an array in JavaScript.

1. Using Array.prototype.indexOf() function

The idea is to compare the index of all items in an array with an index of their first occurrence. If both indices don’t match for any item in the array, you can say that the current item is duplicated. To return a new array with duplicates, use the filter() method.

The following code example shows how to implement this using the indexOf() method:

Download  Run Code

 
The above solution can result in duplicate values in the output. To handle this, you can convert the result into a Set, which stores unique values.

Download  Run Code

2. Using Set.prototype.has() function

Alternatively, to improve performance, you can use the ES6 Set data structure for efficiently filtering the array.

The following solution finds and returns the duplicates using the has() method. This works because each value in the Set has to be unique.

Download  Run Code

That’s all about finding all duplicates in an array in JavaScript.