1

I have a string like "car;bus;airplane;bike"

what is the fastest way to convert it into a set in JavaScript JSX?

Is there something like:

"car;bus;airplane;bike".split(';').toSet()?

So the set will have 'car', 'bus', 'airplane', 'bike' as elements

Dekel
  • 53,749
  • 8
  • 76
  • 105
Jose Cabrera Zuniga
  • 1,843
  • 2
  • 15
  • 39
  • 1
    new Set("car;bus;airplane;bike".split(';')) – Mark Sep 01 '17 at 21:08
  • Similar kind of question, since split converts string to array. [javascript-array-to-set](https://stackoverflow.com/questions/28965112/javascript-array-to-set) – Deepak Singh Sep 01 '17 at 21:14

5 Answers5

3

you can use

let x = new Set("car;bus;airplane;bike".split(';'));

Javscript Set can be initialised as

new Set([iterable]);

you can initialise it with an iterable object

marvel308
  • 9,593
  • 1
  • 16
  • 31
1

Use: new Set("car;bus;airplane;bike".split(';'))

stevenlacerda
  • 953
  • 2
  • 7
  • 20
1

Since you can construct a Set from an itrerable, you could go for:

const theString = "car;bus;airplane;bike";
const theSet = new Set(theString.split(";"));
Vivick
  • 2,051
  • 2
  • 6
  • 19
1

You can use the Set constructor:

s = new Set("car;bus;airplane;bike".split(';'))
console.log(s.size);
console.log(s);

The constructor can take any iterable and convert the objects to be the set's elements.

Note that stackoverflow's snippet will not show the log of s but if you use chrome you can open the console and find the relevant result there.

Dekel
  • 53,749
  • 8
  • 76
  • 105
1

You said "fastest" but all of the answers to date have used strings that they split into arrays and passed into the Set constructor. Cut out the middleman if you really meant "fastest":

const s = new Set(["car","bus","airplane","bike"]);

console.log(s.size);
console.log(s.has("bus"));

Not that the speed of this operation is likely to be significant.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639