This post will discuss how to check if an array contains any duplicate elements in JavaScript.

1. Using ES6 Set

The Set object, introduced in the ES6, can remove duplicate values from an array. The idea is to convert the array to a Set. You can then conclude that the array is not unique if the set’s size is found to be less than the array’s size.

Download  Run Code

2. Using Underscore/Lodash Library

If you don’t want to use Set as an intermediate data structure, you can use the uniq() method from underscore.js or lodash.js libraries. The following code works similarly to the _.uniq(array) method creates a duplicate-free version of an array.

Download Code

3. Using Array.prototype.some() function

Another solution is to find an index of the first occurrence and an index of the last occurrence for each array element. If any item in the array, both indices don’t match, you can say that the array contains duplicates.

The following code example shows how to implement this using JavaScript some() method, along with indexOf() and lastIndexOf() method.

Download  Run Code

 
Note that this solution is not recommended as it has O(N2) complexity.

That’s all about determining whether an array contains duplicates in JavaScript.