0

I have an array like this

      arr=["japan","china","india"];

i want to convert it into a string like this

      str="'japan','china','india'"

join() wouldnt fullfill my requirement as it gives result like below..

      str="japan,china,india"

Any help pls....

1
  • Have you tried searching for similar solutions? maybe formatting the string? Commented Jul 22, 2020 at 6:29

5 Answers 5

1

Use reduce and continue adding to the accumulator.

let res = arr.reduce((acc,curr,ind) => acc += (ind == arr.length -1) ? `'${curr}'` :`'${curr}',` ,'')
Sign up to request clarification or add additional context in comments.

1 Comment

@ArjunChandrasekaran It returns the resulting string, you can store it in a variable. Like I have updated in the answer now
1

Yop,

You can use something like this:

['japan', 'china', 'india'].map(country => `'${country}'`).toString();
// output: 'japan','china','india'

The .map will quote each element of your array, then the .toString will join all the array elements (you can use .join instead if you want another seperator between your elements).

5 Comments

Close, you just need to wrap the result with double quotes :)
Are you sure? I understand from the question the double quotes are just because it's how he format his string, no?
Yeah, they wanted the string to be "'japan','china','india'"
Everyone seem to have understand without them though ^^'
Yeah, my bad sorry, gave you an up.
1

When declaring variables always use var or let:

let arr = ["japan","china","india"];
let str = arr.map(x => "'" + x + "'").join(); // 'japan','china','india'

2 Comments

Nice, you just need to wrap the answer in double quotes.
@Spangle As written on MDN: "String literals can be specified using single or double quotes, which are treated identically, or using the backtick character". source
0
arr.reduce((acc,val, index) => {
if (index === 0 ) { 
acc = acc + `'${val}'`
} else {
acc = acc + `, '${val}'`
}
return acc;
},'');

1 Comment

@ArjunChandrasekaran the whole thing returns a string. Run it an find out.
0

Try this:

<script>
            let arr = ["japan", "china", "india"];
            let str = '';
            for (let i = 0; i < arr.length; i++) {
                if (i < arr.length-1)
                    str += "\'" + arr[i] + "\'" + ",";
                else
                    str += "\'" + arr[i] + "\'";
            }
            console.log(str);
</script>

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.