DEV Community

Discussion on: JavaScript Sets are Excellent!

Collapse
 
averyferrante profile image
Joseph Avery Ferrante • Edited

Cool read!

Fun 'interview style' question that can utilize sets:
Return an array of unique characters from the string 'Hello World', excluding spaces:

*** MY ANSWER ***

new Set('hello world'.split(' ').reduce((acc, cur) => acc.concat([...cur]), []));

  • OR using new flatMap operator -

new Set('hello world'.split(' ').flatMap(cur => [...cur]));

Collapse
 
jacobmgevans profile image
Jacob Evans

Thanks! :)

Collapse
 
bushblade profile image
Will Adams

Fair point I forgot about the space.

Collapse
 
bushblade profile image
Will Adams

Cool I guess you could also do
[...new Set([...'Hello World'])]

Collapse
 
jamesthomson profile image
James Thomson

Almost, it won't exclude the space so you'd have to do something like [...new Set([...'Hello World'.replace(/\s/g, '')])] which kinda ruins how nice and concise this was :(

Thread Thread
 
jacobmgevans profile image
Jacob Evans

All awesome implementations!!