Problems › JavaScript › data
Drop the repeats
A feed sometimes sends the same id twice, and a clean list keeps only the first sighting.
- Keep the first occurrence of each value and drop any that repeat later.
- The relative order of the kept values is untouched.
dedupe(values: list<int>) → list<int>
Where you start
function dedupe(values) {
}
Worked examples
| Call | Result |
|---|---|
dedupe([1,2,3,1,2]) | [1,2,3] |
dedupe([1,1,1]) | [1] |
dedupe([]) | [] |
dedupe([3,1,2,1,3]) | [3,1,2] |
Hint
Carry a set of what you have already seen, and only push a value the first time you meet it.
Reference solution in JavaScript
function dedupe(values) {
const seen = new Set();
const result = [];
for (const v of values) {
if (!seen.has(v)) {
seen.add(v);
result.push(v);
}
}
return result;
}