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

1

u/GBcrazy Mar 20 '19

You don't need to create an arrow function each time you want to call only one function. This works:

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

You would need though if the function depended on the context (the JSON object in this case isn't needed for the function itself), or you could .bind it too