-1

Input Array:

["a,b,c", "foo,bar", "1,2,1", "a"] // should convert to → '"a,b,c","foo,bar","1,2,1","a"'

Now, using toString() or .join("") will produce the unwanted:

var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];

console.log( arr.toString() )
console.log( arr.join(',') )

So, to bypass that, the first which comes to mind is JSON.stringify:

var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];

var s = JSON.stringify(arr).slice(1,-1);

console.log( typeof s, ":" , s )

↑ The above is the wanted result, but i'm sure there's a cleaner way of doing it

Question:

Is this the only way to convert an Array which has string items containing commas to a String?

vsync
  • 118,978
  • 58
  • 307
  • 400
  • 7
    You haven't explained what you want as result. *"Is this the only way to convert an Array which has string items containing commas to a String?"* No, the first examples that you described as "unwanted" are also converting an array to a string. You seem to want the string to be in a specific format. Please explain what that format is. – Felix Kling Jun 20 '18 at 22:22
  • 2
    Eh! Op has 40.5k rep,. And has created a very confusing question, what gives?. – Keith Jun 20 '18 at 22:24
  • 2
    Account hacked or sold? – Pritam Banerjee Jun 20 '18 at 22:26
  • Also please explain why it is relevant that the strings inside the array contain commas. – Felix Kling Jun 20 '18 at 22:27
  • 1
    or just gained rep from a simpler time: https://stackoverflow.com/questions/2332811/capitalize-words-in-string :) – Damon Jun 20 '18 at 22:29
  • I guess the second result is what he really wanted. – Liang Jun 20 '18 at 22:33
  • So what was the question...? – NotoriousPyro Jun 20 '18 at 22:37
  • @Chase You could be right, so maybe `arr.map(i => \`"${i}"\`).join(",")`, but then what about escaping, `"`, or is this not a problem, maybe `stringifyy` is the best option. OP needs to be more specific.. – Keith Jun 20 '18 at 22:38
  • You could use a different delimiter with `join()`. It just needs to be something that isn't in the original strings. – Barmar Jun 20 '18 at 22:51
  • What don't you understand people? I specifically asked how to join array items which contains comas. I came up with a way I think is a hack and I asked if there might be a more "formal" way of doing so. I really don't understand why all the insults and downvotes. very unfriendly, I've been around here for years answering and moderating and helping as much as I can.. – vsync Jun 21 '18 at 07:56
  • I don't think you're going to find anything better than what you have already with `JSON.stringify()`. You've defined a desired output format that only differs from what `JSON.stringify()` produces by a starting and ending character. That's your best shot. Nothing else built into Javascript makes strings that look like raw Javascript string syntax (with external quotes) because that isn't needed or used on an actual string value in the language. – jfriend00 Jun 30 '18 at 00:44

2 Answers2

0

Here is another way to get the same result as with stringify (except when arr contains strings with embedded double-quotes):

arr.reduce((a, c, i) => a + (i > 0 ? ',"' : '"') + c + '"', '')
cybersam
  • 63,203
  • 6
  • 53
  • 76
0

It depends on what "converting to string" means to you. An array is an ordered list of items numerically accessed. A string is a textual representation of that ordered list. If your question is "how to convert an array to a string while still being able to get the original array back," then the most performant answer would be JSON.stringify to convert the Array to a String, then JSON.parse to convert the string back into an array. However, JSON.stringify is only one of the many ways you could convert an array to a string.

A simple way to join all the strings in the array together is either by using Array.prototype.join.call or String.prototype.concat.apply

"use strict";
(function(){
  var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
  console.log( "Array.prototype.join:   ", arr.join("") );
  console.log( "String.prototype.concat: ", String.prototype.concat.apply("", arr) );
})();

Another way you could convert an array to a string is by going through each string in the array and concatenating them together.

"use strict";
(function(){
  var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
  var res = "";
  var i = arr.length;
  var curStr = "";
  while (i--) {
    curStr = arr[i];
    // when the item on the left side is a string, the "+"
    //  operator acts as a concatination operator
    res = res + curStr + ",";
    // res += curStr + ","; // works just as well
    // res += arr[i] + ","; // also works too
  }
  console.log( res );
})();

Using the fact that we can go through each item in the array, and look at each string individually, we can do something like converting each string to a base64 blob, then joining each string with a line break.

"use strict";
(function(window){
  var btoa = window.btoa, atob = window.atob;
  
  function encode(theArray){
    var i = theArray.length, res = "";
    while (i--) res += btoa(theArray[i]) + "\n";
    return res.slice(0,-1);
  }
  function decode(theString){
    var splitted = theString.split("\n");
    var i = splitted.length, res = [];
    while (i--) res.push( atob(splitted[i]) );
    return res;
  }
  
  var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
  var encoded_arr = encode(arr);
  console.log("encoded_arr: ", JSON.stringify(encoded_arr, null, 1).replace(/\\n/g, "\n") );
  var decoded_arr = decode(encoded_arr);
  console.log( "decoded_arr", JSON.stringify(decoded_arr, null, 1).replace(/\\n/g, "\n") );
})(self);

There are countless more ways to join an array of strings together depending on your specific needs. Below are many such examples. Please emphasize that while all the following "work", none of them are as efficient as Array.prototype.join.

function joinWithRegexp(str1, str2) {
    return str1.replace(new RegExp("$"), str2);
}
console.log(joinWithRegexp("Foo", " bar"));

function joinWithPadStart(str1, str2) {
    return str2.padStart(str1.length + str2.length, str1);
}
console.log(joinWithPadStart("Foo", " bar"));

function joinWithPadEnd(str1, str2) {
    return str1.padEnd(str1.length + str2.length, str2);
}
console.log(joinWithPadEnd("Foo", " bar"));

function joinWithTemplateLiteral(str1, str2) {
    return `${str1}${str2}`;
}
console.log(joinWithTemplateLiteral("Foo", " bar"));

var tmpElement = document.createElement("div");
function joinWithDOM(str1, str2) {
    tmpElement.appendChild(document.createTextNode(str1));
    tmpElement.appendChild(document.createTextNode(str2));
    return tmpElement.textContent;
}
console.log(joinWithDOM("Foo", " bar"));

var reader = new FileReader;
function joinWithBlob(str1, str2, thenFunc) {
    reader.onload = function(){ thenFunc( reader.result ); };
    reader.readAsText(new Blob([str1, str2]));
}
joinWithBlob("Foo", " bar", function(result){
    console.log(result);
});
Jack G
  • 4,553
  • 2
  • 41
  • 50
  • 1
    what is all this.. I didn't ask for all this. There aren't any commas in the array's items (strings) and anyway it's more a hack than my own solution.. I'm searching for a cleaner way than mine and not the opposite – vsync Jun 21 '18 at 08:01
  • @vsync There is no cleaner way to convert an array to a string than `JSON.stringify`. However, if you could tell me what your end goal in mind is, then I might be able to tell you a more clean solution than converting an array to a string. – Jack G Jun 21 '18 at 22:48
  • I honestly cannot explain it better than the question.. the question's code was all I need, this is for a script of mine, [Tagify](https://github.com/yairEO/tagify) where tags that might have commas in them needs to be transformed into a string and saved as a value on some input element – vsync Jun 22 '18 at 08:46