I realise it has been a minute since I have last posted anything and in an attempt to try and get myself posting again, I have a very quick tip to share with you all for removing duplicated elements from an array in JavaScript or TypeScript.
Check it out!
const duplicates = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5];
const dedupe = <T>(arr: T[]) => Array.from(new Set(arr));
const unique = dedupe(array);
console.log(unique) // [1, 2, 3, 4, 5]
That's it! How incredibly simple right?
Now because we have used generics, our unique array will be benefit from some lovely type inference!
What do you think?
Let me know if you have any quick and easy methods to achieve the above.
NB. Generics are unique to TypeScript if you are unaware. This means you would want to remove them if you are just using JavaScript.
Top comments (0)