ES6 map array to string without comma

15,490

Solution 1

.toString() of the array object uses Array.prototype.join method for converting the array into a string. The .join method by default uses , for joining the elements. You can replace the .toString() with .join('').

Solution 2

In your code, you are using template literals which returns you a string and hence the code

 ${errors.map(error => `<li>${error}</li>`)}

is converted to a string using a toString() function which by default joins the returned array with a ,.

You can make use of join with anly other separator like

{`
  Precisa de corrigir os seguintes problemas antes de publicar o anúncio:</br>
  <ul>
    ${errors.map(error => `<li>${error}</li>`).join(' ')}
  </ul>
`}
Share:
15,490

Related videos on Youtube

Fábio Santos
Author by

Fábio Santos

Updated on September 15, 2022

Comments

  • Fábio Santos
    Fábio Santos over 1 year

    I am trying to map a list of errors into a list that I will show in a tooltip. The list added, but there's a , added between every li element.

    I guess this is because this basically does errors.map(error => ...).toString() in the end. Any ideas how I can map the strings in errors array without having this comma added?

    data-tip = {`
      Precisa de corrigir os seguintes problemas antes de publicar o anúncio:</br>
      <ul>
        ${errors.map(error => `<li>${error}</li>`)}
      </ul>
    `}
    
    • Jai
      Jai almost 7 years
      just replace to this and see: ${errors.map(error => <li>${error}</li>)} remove the backtics of li.
  • KarelG
    KarelG almost 7 years
    in addition to this post, check also .join() doc.
  • Fábio Santos
    Fábio Santos almost 7 years
    You have an error here. .join(' ') should be inside the brackets