Removing duplicate elements from an array is one of the most common tasks in everyday JavaScript — cleaning up API responses, deduplicating user input, or merging two lists. Modern JavaScript makes this almost trivial with the Set object, but it’s worth knowing the manual approach too.
JavaScript Program to Remove Duplicates Using Set
const numbers = [1, 2, 2, 3, 4, 4, 4, 5, 1];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);
Output:
[ 1, 2, 3, 4, 5 ]
JavaScript Program to Remove Duplicates Without Set
If you need to support an environment without Set, or want to understand what’s happening under the hood, you can do the same thing by iterating over the array and only keeping elements you haven’t seen yet.
function removeDuplicates(arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
if (!result.includes(arr[i])) {
result.push(arr[i]);
}
}
return result;
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 4, 5, 1]));
Output:
[ 1, 2, 3, 4, 5 ]
The Set version is O(n) and should be your default choice. The manual version using includes() is O(n²) in the worst case because includes() itself scans the growing result array on every iteration — fine for small arrays, but worth avoiding on large datasets where Set (or a plain object/Map used as a lookup table) scales much better.
