Find all duplicates in an array in JavaScript
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:
|
1 2 3 4 5 6 7 8 9 |
const arr = [ 5, 3, 4, 2, 3, 7, 5, 6 ]; const findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) !== index) const duplicates = findDuplicates(arr); console.log(duplicates); /* Output: [ 3, 5 ] */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
function findDuplicates(arr) { const filtered = arr.filter((item, index) => arr.indexOf(item) !== index); return [...new Set(filtered)] } const arr = [ 5, 3, 4, 2, 3, 7, 5, 6 ]; const duplicates = findDuplicates(arr); console.log(duplicates); /* Output: [ 3, 5 ] */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function findDuplicates(arr) { const distinct = new Set(arr); // to improve performance const filtered = arr.filter(item => { // remove the element from the set on very first encounter if (distinct.has(item)) { distinct.delete(item); } // return the element on subsequent encounters else { return item; } }); return [...new Set(filtered)] } const arr = [ 5, 3, 4, 2, 3, 7, 5, 6 ]; const duplicates = findDuplicates(arr); console.log(duplicates); /* Output: [ 3, 5 ] */ |
That’s all about finding all duplicates in an array 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 :)