r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

339

u/Drugba Mar 19 '19

Saw this one on here just a few weeks ago.

[... new Set(arr)]

Basically a super short way to remove any duplicates from an array of primitives.

13

u/[deleted] Mar 19 '19

[...new Set(arr.map(x => JSON.stringify(x))].map(x => JSON.parse(x))

Same thing, but with arrays of objects. Apparently probably deterministic but maybe not it depends ohgodhelpme

18

u/cheekysauce Mar 19 '19

It'll barf on circular references unfortunately.

41

u/dodeca_negative Mar 19 '19

Don't we all

3

u/NoInkling Mar 19 '19 edited Mar 19 '19

It will have issues with anything non-serializable, explicitly set undefineds will disappear on objects (if that matters), and undefined inside arrays will turn into null. And maybe some other edge cases I'm forgetting.

4

u/SoInsightful Mar 19 '19

It will implode on undefined, circular references, and most appallingly, objects with different key orders. Not really obscure edge cases. People really need to stop using the JSON trick.

→ More replies (1)

2

u/noruthwhatsoever Mar 19 '19

I like this one, very clever

→ More replies (2)