1

i have this

string = "Art,fitness"

and i want a array like this

[[Art], [Fitnnes]]

if i do string.spli(',')

i got ["Art", "Fitnnes"]

And is not the output i need, also i try

JSON.parse("[" + string.replace(/'/g, '"') + "]");

but dont work and give me [ 'Art,Fitnnes' ];

i need to do a map before the split to create a new array or there are a simple way to do this

4 Answers4

4

You can do it like this

const string = "Art,fitness"

const result = string.split(",").map(item => [item])

console.log(result)

First, we split() the string on the ,, then we map through the outcome array and return the item in another array.

axtck
  • 3,707
  • 2
  • 10
  • 26
3

The below code works well

const string = "Art,fitness";
const newArray = string.split(',').map(str=>[str]);
Suraj Sharma
  • 777
  • 6
  • 10
0
const string = "Art, fitness";

console.log(string.split(',').map(a => [a]));

Loop over the split values with the .map operator and return them as array.

Akash Kriplani
  • 162
  • 1
  • 12
-2

Instead of splitting the list and mapping each item to an array containing one item, you could alternatively manipulate the input string by converting it to JSON and then parsing the JSON as a two-dimensional array.

  1. First, process all tokens that are a sequence of non-delimiters (ignoring white-space) and wrap them in quotes and brackets (inner-array).
  2. Next, surround the string with brackets (outer-array).
  3. Finally, you can parse the string as JSON data.

const strListToMatrix = listStr =>
  JSON.parse(
    listStr
      .replace(/\s*([^,]+)\s*/g, '["$1"]')
      .replace(/(.+)/, '[$1]'));

console.log(strListToMatrix('Art,fitness'));
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132