Reputation: 1147
I have an array that looks like this:
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
I want to return the results like this:
'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'
This is what I have done so far:
includes = tagsI.map(tag => `'${tag}'`).join(',')
But this only separates by commas and single quotes the values.. not the values of the values as well.
How can I do this?
Thank you
Upvotes: 0
Views: 40
Reputation: 4991
How about using reduce :
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];
//V1 : compatible with all browsers
var result = array.reduce((acc, elem, index, arr)=>{
var n_arr = elem.split(",").map(map_elem=> `'${map_elem}'`);
n_arr.forEach(fe_elem => acc.push(fe_elem));
return acc;
}, []).join(",");
console.log(result);
document.querySelector("#res1").innerHTML = result;
//V2: compatible with some browsers
var result2 = array.reduce((acc, elem, index, arr)=>{
var n_arr = elem.split(",").map(map_elem=>`'${map_elem}'`);
acc.push(...n_arr);
return acc;
}, []).join(",");
console.log(result2)
document.querySelector("#res2").innerHTML = result2;
<body>
<p id="res1"></p>
<p id="res2"></p>
</body>
The principle is the following :
We have an initial Array "array" in which we stored strings (["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"])
For each string in the array:
PS: If you want an array instead of a string, just remove the join(",")
Upvotes: 1
Reputation: 191976
Join the items of the array to a single string with commas. Split the string by the comma separators, map the items to the required format, and join again with commas.
const array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
const result = array
.join(',')
.split(',')
.map(tag => `'${tag}'`)
.join(',');
console.log(result);
Upvotes: 2
Reputation: 4066
split tag
by comma and use another map
var tagsI = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
var result = tagsI.map(tag => tag.split(',').map(tag => `'${tag}'`)).join(',');
console.log(result)
Upvotes: 1
Reputation: 17279
You'll first need to split each element in the array.
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];
var split = array.map(v => v.split(","));
var flattened = [].concat.apply([], split);
var str = flattened.join(",");
Upvotes: 0