There's actually a very easy and performant way to remove duplicate elements from an array by leveraging the built-in behaviour of Set
:
/**
* Construct a copy of an array with duplicate items removed.
* Where duplicate items exist, only the first instance will be kept.
*/
function removeDups<T>(array: T[]): T[] {
return [...new Set(array)];
}
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
console.log(removeDups(names)); // ["John", "Paul", "George", "Ringo"]
TypeScript Playground
That function converts your array to a Set
, which removes duplicates faster than any native loop through the array will manage, and then uses spread syntax to convert that Set
back into a new array.
By making the removeDups
function use a generic type, it can be used with any type of array, not just string arrays like your example.
To convert the function you have written into TypeScript, here's what you can use:
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
function removeDups(names: string[]): string[] {
let unique: Record<string, boolean> = {};
names.forEach(function(i) {
if(!unique[i]) {
unique[i] = true;
}
});
return Object.keys(unique);
}
removeDups(names)
TypeScript Playground
This uses the utility type Record
for your unique
object's type. However, due to how Object.keys
works, this function will only be able to work on arrays of strings. If you want to use this approach with all types of array, you could consider using a Map
instead so you can index it by other types.
That would look something like this:
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
function removeDups<T>(names: T[]): T[] {
let unique: Map<T, boolean> = new Map();
names.forEach(function(i) {
if(!unique.has(i)) {
unique.set(i, true);
}
});
return Array.from(unique.keys());
}
console.log(removeDups(names)); // ["John", "Paul", "George", "Ringo"]
TypeScript Playground