How to convert Set to string with space?

42,295

You can use Array.from:

Array.from(foo).join(' ')

or the spread syntax:

[...foo].join(' ')
Share:
42,295
KimchiMan
Author by

KimchiMan

Updated on July 05, 2022

Comments

  • KimchiMan
    KimchiMan almost 2 years

    I want to convert JavaScript Set to string with space.

    For example, if I have a set like:

    var foo = new Set();
    foo.add('hello');
    foo.add('world');
    foo.add('JavaScript');
    

    And I'd like to print the string from the set: hello world JavaScript (space between each element).

    I tried below codes but they are not working:

    foo.toString(); // Not working
    String(foo); // Not working
    

    Is there simplest and easiest way to convert from Set to string?

  • Simona Adriani
    Simona Adriani over 5 years
    Array.from is not supported by internet Explorer, if someone has to maintain the compatibility of its script, any other suggestion?
  • Bence László
    Bence László about 4 years
    Array.from is significantly faster in large sets, though.
  • Clio Orgyán
    Clio Orgyán about 2 years
    Use a polyfill @SimonaAdriani