Skip to content Skip to sidebar Skip to footer

Es6 Map Array To String Without Comma

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 basicall

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>
`}

Solution 3:

You can try this way ::

let arrayOfStr = [10, 20, 45, 12, 65 ];

let myNumberOfStr = arrayOfStr.map( number =>`myNumber_${number}` ).join(' ');

console.log(myNumberOfStr); 
// "myNumber_10 myNumber_20 myNumber_45 myNumber_12 myNumber_65"

Solution 4:

Just use reduce. Like this:

data-tip = {`
  Precisa de corrigir os seguintes problemas antes de publicar o anúncio:</br>
  <ul>
    ${errors.reduce(
      (prevError, currentError) => `${prevError}<li>${currentError}</li>`, '',
    )}
  </ul>
`}

Post a Comment for "Es6 Map Array To String Without Comma"