admin管理员组文章数量:1312778
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)
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)
Share
Improve this question
asked Aug 9, 2020 at 4:55
NandoNando
1031 silver badge5 bronze badges
2
- all javascript is proper typescript – frozen Commented Aug 9, 2020 at 4:56
-
1
@frozen not when you enable the
strict
pile flag, which is the default withtsc --init
... – Patrick Roberts Commented Aug 9, 2020 at 5:18
4 Answers
Reset to default 5There'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
names = ['John', 'Paul', 'George', 'Ringo', 'John'];
removeDups(names) {
let unique = {};
this.names.forEach((i) => {
if(!unique[i]) {
unique[i] = true;
}
});
return Object.keys(unique);
}
Then call removeDups
from where you want
Here is another way:
names = ['John', 'Paul', 'George', 'Ringo', 'John'];
removeDups(names) {
return this.names.filter((elem, index, self)=> {
return index === self.indexOf(elem);
})
}
In this case, you just have to add types
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
function removeDups(names: string[]) {
let unique: any = {};
names.forEach(function(i: string) {
if(!unique[i]) {
unique[i] = true;
}
});
return Object.keys(unique);
}
removeDups(names)
typescript playground
Here is a simple and generic method to de-duplicate any array.
Js:
deDup = (arr) => arr.reduce((acc, current) => {
if(!acc.includes(current)) acc.push(current)
return acc
}, [])
Ts:
deDup = (arr: any[]) => arr.reduce((acc, current) => {
if(!acc.includes(current)) acc.push(current)
return acc
}, [] as any[])
Since this by definition is reducing an array by removing duplicate values, call reduce being sure to pass in an initial value of a new empty array (accumulator). On each index (current) if it's not in the accumulator array then add it, then return the accumulator array. This will quickly return a new array to the caller without any duplicates.
本文标签: javascriptRemove duplicates from array in typescriptStack Overflow
版权声明:本文标题:javascript - Remove duplicates from array in typescript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741877473a2402546.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论