Find the first duplicate in an array in JavaScript
Intermediate · 4 min read
Finding the first repeated value in a list sounds simple, and it is a popular interview question because the word "first" hides a trap. In real code you need it to spot a username that was registered twice, a seat booked twice, or the first repeated reading in a stream of sensor data.
In this tutorial you will write firstDuplicate, which scans from left to right and returns the first value that appears for the second time. Then you will list every duplicated value, and answer "is there any duplicate at all?" in one line. You should know arrays, for...of loops and the basics of a Set.
What "first" means
Take [5, 9, 9, 5]. Both 5 and 9 repeat. Which one is the first duplicate?
5 appears first, so it is tempting to say 5. But "first duplicate" means the first moment you meet a value you have already seen. Walk through it:
- index 0: 5, new.
- index 1: 9, new.
- index 2: 9, seen before. This is the first repeat.
- index 3: 5, seen before, but too late.
So the answer is 9. The second 9 arrives at index 2, before the second 5 at index 3.
A Set as a memory
A Set holds each value once. add puts a value in, and has checks whether it is there. Both are fast, however big the Set gets.
const seen = new Set();
seen.add(5);
console.log(seen.has(5)); // true
console.log(seen.has(9)); // false
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
39 Find the first duplicate
fairReturn the first value that appears twice, scanning left to right. [5, 9, 9, 5] should give 9, not 5. Then list every duplicated value.
Stuck? Three hints, smallest first
- 1. Walk once, remembering what you have seen in a
Set, and stop at the first value already in it. - 2. "First duplicate" means the first second occurrence, so
[5, 9, 9, 5]gives 9. - 3.
new Set(xs).size !== xs.lengthanswers "is there any duplicate" in one line.
Step 1: remember and stop
Walk the list once. If the value is already in seen, that is the answer, so return it. Otherwise remember it and keep going.
function firstDuplicate(xs) {
const seen = new Set();
for (const v of xs) {
if (seen.has(v)) return v;
seen.add(v);
}
return undefined;
}
console.log(firstDuplicate([1, 2, 3, 2])); // 2
console.log(firstDuplicate([5, 9, 9, 5])); // 9
console.log(firstDuplicate([1, 2, 3])); // undefined
console.log(firstDuplicate([])); // undefined
return inside the loop stops the whole function, so the scan ends as soon as it finds the answer. If the loop finishes without finding a repeat, the function returns undefined, meaning "no duplicate".
This makes one pass over the list. An approach that uses indexOf for each item looks through the list again and again, which gets slow as the list grows.
Step 2: NaN and objects
function firstDuplicate(xs) {
const seen = new Set();
for (const v of xs) {
if (seen.has(v)) return v;
seen.add(v);
}
return undefined;
}
console.log(firstDuplicate([NaN, NaN])); // NaN
const shared = {};
console.log(firstDuplicate([shared, {}, shared]) === shared); // true
console.log(firstDuplicate([{ id: 1 }, { id: 1 }])); // undefined
NaN === NaN is false in JavaScript, but a Set still treats NaN as matching itself, so it is caught. Objects count as duplicates only when they are the very same object, which is called identity. Two separate { id: 1 } objects are not a duplicate, even though they look alike. For that, compare a key such as the id instead.
Step 3: every duplicated value
Now list every value that repeats, once each. Use two Sets: one for values seen once, one for values seen again.
const allDuplicates = (xs) => {
const seen = new Set();
const twice = new Set();
for (const v of xs) (seen.has(v) ? twice : seen).add(v);
return [...twice];
};
console.log(allDuplicates([1, 2, 2, 3, 3, 3])); // [ 2, 3 ]
The loop line is compact, so read it slowly. seen.has(v) ? twice : seen picks a Set: twice if we have met v before, seen if not. Then .add(v) adds to whichever one was picked. Because twice is a Set too, a value seen three times is still listed once.
Step 4: is there any duplicate?
Sometimes you only need yes or no. A Set drops repeats, so if it ends up smaller than the list, something repeated.
const hasDuplicate = (xs) => new Set(xs).size !== xs.length;
console.log(hasDuplicate([1, 2, 3])); // false
console.log(hasDuplicate([1, 1])); // true
This is one line, but it always reads the whole list. firstDuplicate can stop early, so prefer it when the list is long and you expect a repeat near the start.
The full solution
The panel has firstDuplicate, allDuplicates and hasDuplicate, and runs them on every case above. Press Run and check the [5, 9, 9, 5] line.
function firstDuplicate(xs) {
const seen = new Set();
for (const v of xs) {
if (seen.has(v)) return v;
seen.add(v);
}
return undefined;
}
const allDuplicates = (xs) => {
const seen = new Set();
const twice = new Set();
for (const v of xs) (seen.has(v) ? twice : seen).add(v);
return [...twice];
};
const hasDuplicate = (xs) => new Set(xs).size !== xs.length;
const shared = {};
console.log('[1, 2, 3, 2] ->', firstDuplicate([1, 2, 3, 2]));
console.log('[5, 9, 9, 5] ->', firstDuplicate([5, 9, 9, 5]), '<- 9 repeats first');
console.log('[1, 2, 3] ->', firstDuplicate([1, 2, 3]));
console.log('all duplicates:', allDuplicates([1, 2, 2, 3, 3, 3]));
console.log('any duplicate?', hasDuplicate([1, 2, 3]), hasDuplicate([1, 1]));
console.log('NaN ->', firstDuplicate([NaN, NaN]), '<- a Set can hold it');
console.log('objects ->', firstDuplicate([shared, {}, shared]) === shared);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a repeat is found', firstDuplicate([1, 2, 3, 2]), 2);
test('the FIRST repeat wins, not the smallest', firstDuplicate([5, 9, 9, 5]), 9);
test('no repeat gives undefined', firstDuplicate([1, 2, 3]), undefined);
test('an empty array is fine', firstDuplicate([]), undefined);
test('NaN is caught, because a Set compares with SameValueZero', Number.isNaN(firstDuplicate([NaN, NaN])), true);
test('every duplicated value, once each', allDuplicates([1, 2, 2, 3, 3, 3]), [2, 3]);
test('the size comparison answers the yes/no question', [hasDuplicate([1, 2, 3]), hasDuplicate([1, 1])], [false, true]);
test('objects repeat only by identity', firstDuplicate([shared, {}, shared]) === shared, true);
test('so two lookalike objects are not a duplicate', firstDuplicate([{ id: 1 }, { id: 1 }]), undefined);
The definition is the exercise. "First duplicate" almost always means the first position at which a value is seen for the second time, which is why [5, 9, 9, 5] answers 9 — the second 9 arrives at index 2, the second 5 at index 3. Sorting first, or scanning for the smallest repeated value, answers a different question.
One pass with a Set is O(n) and stops as early as possible. The indexOf-based alternative is O(n²) and, as exercise 37 showed, silently misses NaN. The last two assertions are the honest limit of all of this: duplicates are identity-based, so records that are "the same" by id need a key function.
Common mistakes
- Returning the value that appears first. For
[5, 9, 9, 5], that gives 5. The first repeat is 9. - Sorting the list first. That loses the original order, so it answers a different question.
- Expecting lookalike objects to match. A Set compares objects by identity. Compare a key such as
idinstead.
Try it yourself
- Change
firstDuplicateto return the index of the first repeat instead of the value. - Write
firstDuplicateBy(xs, keyOf)that finds the first repeated key, for example the first repeated email. - Find the first letter that repeats in
'programming'.