Remove comma from string literal

Viewed 55

I want to concatenate string with array Item.

I tried following.

const str = "I have following things:"
const arr = ["chair", "table", "bed"];


const tootlTipText = `${str}
${arr.map(item => `- ${item} \n`)}`;
                

console.log(tootlTipText);

It display , in between. I tried to find and can't find what is the issue.

2 Answers

The problem is that by default, when you convert an array to a string, it's done as though you called .join(","). To avoid that, call join yourself with whatever separator you want, perhaps "":

const str = "I have following things:"
const arr = ["chair", "table", "bed"];


const tootlTipText = `${str}
${arr.map(item => `- ${item} \n`).join("")}`;
                

console.log(tootlTipText);

Alternatively, you could use a simple loop with string concatenation:

const str = "I have following things:"
const arr = ["chair", "table", "bed"];

let tootlTipText = `${str}\n`;
for (const item of arr) {
    tootlTipText += `- ${item} \n`;
}

console.log(tootlTipText);

Some folks would also use reduce for this; personally I don't like reduce except in functional programming with predefined, tested reducers, but:

const str = "I have following things:"
const arr = ["chair", "table", "bed"];

const tootlTipText = arr.reduce(
    (str, item) => str + `- ${item} \n`,
    `${str}\n`
);

console.log(tootlTipText);

Array.prototype.map() returns an array. It should be converted to string.

const tootlTipText = `${str}
    ${arr.map(item => `- ${item} \n`).join('')}`;
Related