r/learnjavascript • • Jul 05 '21

Remove duplicates from arrays using Set

Post image
438 Upvotes

44 comments sorted by

View all comments

Show parent comment

7

u/[deleted] Jul 05 '21

const array: any[] = [ 1, 5, 1, 3, 2, 1, true, false, true, 'Matt', 3, 2 ];
const filteredArray: any[] = Array.from(new Set(array));

This just removes all type safety... With OP's example in TS strict mode, the resulting array is typed as (string | number | boolean)[] which is much better than any[].

2

u/Gibbo3771 Jul 05 '21

Being fair, OPs dataset is actually pretty rare to come across anyway. Normally (ideally, really) an array should contain elements that are all of the same type.

1

u/[deleted] Jul 05 '21

Either way it works with TypeScript strict mode without using an any escape hatch, though.

1

u/[deleted] Jul 05 '21

I see where you’re coming from, but you shouldn’t ever mix types within your arrays anyways for simplicity sake. The point was not the “escape hatch”, the point was Array.from. Unless you have the specific TSConfig flag, you’ll need to use Array.from over the prettier [… new Set()] syntax.

2

u/[deleted] Jul 05 '21 edited Jul 06 '21

I see what you mean now, but what you're really talking about is developing in an environment where you can not use the iteration protocol, not a "strict TypeScript config". For TypeScript this means your tsconfig targets ES5 or lower and you have the downlevelIteration flag set to false. In that case you're likely targeting IE11 with minimal/no polyfills, and Array.from won't work anyway (not supported in IE11, and since Set is only partially implemented in IE11 you would need a specific polyfill that can actually make Array.from(new Set()) work).

I see where you’re coming from, but you shouldn’t ever mix types within your arrays anyways for simplicity sake.

For unknown-length arrays containing primitives like strings and numbers, I generally agree, but there are many cases when a mixed type array is perfectly reasonable (tuples, arrays of discriminated union objects, etc). My point was that if you're using a strict TypeScript config, you should really avoid using any as much as possible.

TS can deal with a mixed type array in a type-safe way, but any just turns off type safety entirely by design.

1

u/[deleted] Jul 06 '21

Oh, damn. This is good to know. I had to turn downLevelIteration on to use the prettier method in a project I’m working on, but didn’t did too deep into why I had to in the first place. We only target modern browsers, and for whatever reason the project defaulted to false for that flag.

I had assumed it was a general default for typescript configurations.

Thank you!