Check if an array contains duplicates in JavaScript
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function hasDuplicates(arr) { return new Set(arr).size !== arr.length; } var arr = [ 2, 4, 6, 5, 4 ]; if (hasDuplicates(arr)) { console.log("Duplicate elements found."); } else { console.log("No Duplicates found."); } /* Output: Duplicate elements found. */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var _ = require('underscore'); function hasDuplicates(arr) { return _.uniq(arr).length !== arr.length; } var arr = [ 2, 4, 6, 5, 4 ]; if (hasDuplicates(arr)) { console.log("Duplicate elements found."); } else { console.log("No Duplicates found."); } /* Output: Duplicate elements found. */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function hasDuplicates(arr) { return arr.some(x => arr.indexOf(x) !== arr.lastIndexOf(x)); } var arr = [ 2, 4, 6, 5, 4 ]; if (hasDuplicates(arr)) { console.log("Duplicate elements found."); } else { console.log("No Duplicates found."); } /* Output: Duplicate elements found. */ |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)