0

I am having this array of string:

color = ['red','blue','purple'];

I want to print a message that says:

color in ('red','blue','purple')

If I write this:

color.forEach((c) => {
      console.log(`color in ('${c}')`);
    });

I am getting this message:

color in ('red') color in ('blue') color in ('purple')

How can I get the first message?

1
  • don't use forEach simply use console.log(`color in ('${color}'))` Commented Feb 13, 2020 at 10:40

4 Answers 4

3

You'd need to map each color to add quotes to it, then join them together:

const colors = ['red','blue','purple'];
console.log(`color in (${ colors.map(c => `'${c}'`).join(',') })`);

Though I'm not sure why you'd do it specifically that way. For debugging purposes, just console.log('color in', colors) would do just fine. For user-visible messages, you'd probably just use colors.join(', '), and/or more elaborate formatting using ..., ... and ....

Sign up to request clarification or add additional context in comments.

Comments

0

You can try this one

color = ['red','blue','purple'];

console.log(`color in (${color.map(item => "'" + item + "'").toString()})`); // color in ('red','blue','purple')

Comments

0

Use the forEach loop in this way

var color = ['red','blue','purple'];
var str='color in (';
color.forEach(e=>str+="'"+e+"',")
str=str.substring(0,str.length-1)+')';
console.log(str)

Comments

0

Another alternative could be the function Array.from.

You can call the function Array.prototype.join without param and the comma will be used as a separator.

Array.prototype.join()

Param separator Optional

Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If separator is an empty string, all elements are joined without any characters in between them.

const colors = ['red','blue','purple'];
console.log(`color in (${ Array.from(colors, c => `'${c}'`).join() })`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.