0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Find Duplicate Elements in Array

You can find duplicate elements in an array using JavaScript by filtering elements that appear more than once, for example: const duplicates = arr.filter((item, index) => arr.indexOf(item) !== index);
📋

Examples

Input[1, 2, 3, 4]
Output[]
Input[1, 2, 2, 3, 4, 4, 5]
Output[2, 4]
Input['a', 'b', 'a', 'c', 'b']
Output['a', 'b']
🧠

How to Think About It

To find duplicates, look at each element and check if it appears again later in the array. If yes, it is a duplicate. Collect these duplicates without repeating them in the result.
📐

Algorithm

1
Get the input array.
2
Create an empty list to store duplicates.
3
For each element, check if it appears again in the array after its current position.
4
If yes and not already in duplicates list, add it to duplicates.
5
Return the list of duplicates.
💻

Code

javascript
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));
Output
[2, 4]
🔍

Dry Run

Let's trace [1, 2, 2, 3, 4, 4, 5] through the code

1

Start with empty duplicates

duplicates = []

2

Check element 1 at index 0

arr.indexOf(1) = 0, current index = 0, no duplicate

3

Check element 2 at index 1

arr.indexOf(2) = 1, current index = 1, no duplicate yet

4

Check element 2 at index 2

arr.indexOf(2) = 1, current index = 2, duplicate found, add 2

5

Check element 3 at index 3

arr.indexOf(3) = 3, current index = 3, no duplicate

6

Check element 4 at index 4

arr.indexOf(4) = 4, current index = 4, no duplicate yet

7

Check element 4 at index 5

arr.indexOf(4) = 4, current index = 5, duplicate found, add 4

8

Check element 5 at index 6

arr.indexOf(5) = 6, current index = 6, no duplicate

IndexElementindexOf(Element)Is Duplicate?Duplicates List
010No[]
121No[]
221Yes[2]
333No[2]
444No[2]
544Yes[2, 4]
656No[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

Using a frequency map
javascript
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]));
This method is faster for large arrays because it counts occurrences in one pass.
Using Set to track seen elements
javascript
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]));
This method uses Sets for efficient lookups and avoids duplicates automatically.

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.

ApproachTimeSpaceBest For
indexOf in loopO(n²)O(n)Small arrays, simple code
Frequency mapO(n)O(n)Large arrays, faster performance
Set trackingO(n)O(n)Efficient and clean for duplicates
💡
Use a Set to track seen items for better performance when finding duplicates.
⚠️
Beginners often forget to check if a duplicate is already added, causing repeated duplicates in the result.