JavaScript Program to Find Duplicate Elements in Array
const duplicates = arr.filter((item, index) => arr.indexOf(item) !== index);Examples
How to Think About It
Algorithm
Code
const findDuplicates = arr => { const duplicates = []; arr.forEach((item, index) => { if (arr.indexOf(item) !== index && !duplicates.includes(item)) { duplicates.push(item); } }); return duplicates; }; const array = [1, 2, 2, 3, 4, 4, 5]; console.log(findDuplicates(array));
Dry Run
Let's trace [1, 2, 2, 3, 4, 4, 5] through the code
Start with empty duplicates
duplicates = []
Check element 1 at index 0
arr.indexOf(1) = 0, current index = 0, no duplicate
Check element 2 at index 1
arr.indexOf(2) = 1, current index = 1, no duplicate yet
Check element 2 at index 2
arr.indexOf(2) = 1, current index = 2, duplicate found, add 2
Check element 3 at index 3
arr.indexOf(3) = 3, current index = 3, no duplicate
Check element 4 at index 4
arr.indexOf(4) = 4, current index = 4, no duplicate yet
Check element 4 at index 5
arr.indexOf(4) = 4, current index = 5, duplicate found, add 4
Check element 5 at index 6
arr.indexOf(5) = 6, current index = 6, no duplicate
| Index | Element | indexOf(Element) | Is Duplicate? | Duplicates List |
|---|---|---|---|---|
| 0 | 1 | 0 | No | [] |
| 1 | 2 | 1 | No | [] |
| 2 | 2 | 1 | Yes | [2] |
| 3 | 3 | 3 | No | [2] |
| 4 | 4 | 4 | No | [2] |
| 5 | 4 | 4 | Yes | [2, 4] |
| 6 | 5 | 6 | No | [2, 4] |
Why This Works
Step 1: Check each element's first occurrence
Using indexOf finds the first position of an element in the array.
Step 2: Compare current index with first occurrence
If current index is different from first occurrence, the element is a duplicate.
Step 3: Avoid adding duplicates multiple times
Check if the element is already in the duplicates list before adding it.
Alternative Approaches
const findDuplicates = arr => { const freq = {}; const duplicates = []; arr.forEach(item => { freq[item] = (freq[item] || 0) + 1; }); for (const key in freq) { if (freq[key] > 1) duplicates.push(isNaN(key) ? key : Number(key)); } return duplicates; }; console.log(findDuplicates([1,2,2,3,4,4,5]));
const findDuplicates = arr => { const seen = new Set(); const duplicates = new Set(); arr.forEach(item => { if (seen.has(item)) { duplicates.add(item); } else { seen.add(item); } }); return [...duplicates]; }; console.log(findDuplicates([1,2,2,3,4,4,5]));
Complexity: O(n²) time, O(n) space
Time Complexity
The main method uses indexOf inside a loop, which causes nested iteration, resulting in O(n²) time.
Space Complexity
Extra space is used to store duplicates, which can be up to O(n) in the worst case.
Which Approach is Fastest?
Using a frequency map or Sets reduces time complexity to O(n) by avoiding nested loops.
| Approach | Time | Space | Best For |
|---|---|---|---|
| indexOf in loop | O(n²) | O(n) | Small arrays, simple code |
| Frequency map | O(n) | O(n) | Large arrays, faster performance |
| Set tracking | O(n) | O(n) | Efficient and clean for duplicates |