简体   繁体   中英

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

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); 

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) 

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(",")

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(",");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM