Write a function findDuplicates(arr) that returns an array of values that appear more than once in the input array, each value listed only once, in the order they first repeat. For example, findDuplicates([1,2,3,2,4,1]) should return [2,1].
function findDuplicates(arr) {
// your code here
}
Rules:
Plain JavaScript only, no libraries
Return values in order of first repeat, not first appearance
Each duplicate value should appear only once in the result
Solution should be about 3 to 10 lines
Post your solution as a reply. Answer goes up in about a day.
function findDuplicates(arr) {
let unique = new Set();
let duplicates = new Set();
for (let i = 0; i < arr.length; i++) {
let current = arr[i];
if (!unique.has(current)) {
unique.add(current);
} else {
duplicates.add(current);
}
}
return duplicates;
}
console.log(findDuplicates([1,2,3,2,4,1]));
function findDuplicates(arr) {
let unique = new Set();
let duplicates = new Set();
for (let i = 0; i < arr.length; i++) {
let current = arr[i];
if (!unique.has(current)) {
unique.add(current);
} else {
duplicates.add(current);
}
}
// Convert the Set to an Array before returning
return [...duplicates];
}
console.log(findDuplicates([1, 2, 3, 2, 4, 1]));
Challenge solution: Track how many times each value has been seen with a Map, and push a value into the result array at the exact moment its count first becomes 2, giving the order of first repeat.
One way to do it:
function findDuplicates(arr) {
const counts = new Map();
const result = [];
for (const val of arr) {
const count = (counts.get(val) || 0) + 1;
counts.set(val, count);
if (count === 2) {
result.push(val);
}
}
return result;
}
Why:
Each element is counted as it is encountered, and a value is added to the result only once, exactly when its occurrence count transitions from 1 to 2, which naturally captures the order in which values first repeat. Using a Map avoids duplicate entries and keeps the logic O(n).