The Python idiom in the subject line
set('pdf ppt tif tiff jpg jpeg'.split())
illustrates a fairly compact way to create a set of strings.1 I’m looking for a similarly compact idiom to create a set in JavaScript. (NB: I am not interested in merely creating a list of strings.)
I understand that the standard approach to sets in JS is to use objects (keys are set elements, values immaterial), but I have not hit upon a comparably succinct way to create such a set in JS.
FWIW, the idiom I’m looking for is intended for a bookmarklet (hence the emphasis on succinctness).
Thanks!
1 For those unfamiliar with Python, the inner expression just evaluates to the list of strings obtained by splitting the invoking string object at the whitespace; this list is then the argument to the set constructor.
Edit: emphasized that I’m looking for a set (i.e. object), not a list of strings.
JavaScript doesn’t have a
settype but you need a helper function to easily create it from a string (or from anArray).Here’s such a helper function which will allow you to call
.set()on a string and get an object mapping the items from the string to some value (trueif none is specified):Demo:
Since you prefer something succinct, this might be a solution for you if you only need it for a single string:
In that case I would consider simply using an object literal though… that’s most likely the shortest solution unless you have a ton of elements.