Walker
Walker

Reputation: 1147

javascript array - separate values and values of values by single quotes

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

Answers (4)

Vivick
Vivick

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:

    1. We split in an array the said string by ","
    2. We surround each element of this array by quotes
    3. We add each of these elements to the array that will be used as the result variable
  • We created a string joining by ","



PS: If you want an array instead of a string, just remove the join(",")

Upvotes: 1

Ori Drori
Ori Drori

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

Farnabaz
Farnabaz

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

Steven Wexler
Steven Wexler

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

Related Questions