I am new to typescript, and i've been having some problems in using my javascript skills. For example, can someone help me to write this exactly same javascript code below in typescript?
If not possible at all, any typescript function that will render the expected output (array without duplicate values).
This is just a simple way to remove duplicates from an array, but seems like typescript doesn't let me define an empty object... I'm not sure...
The output of the code below is: ['John', 'Paul', 'George', 'Ringo']
Thanks!
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
function removeDups(names) {
let unique = {};
names.forEach(function(i) {
if(!unique[i]) {
unique[i] = true;
}
});
return Object.keys(unique);
}
removeDups(names)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With