-2

I am new to stack overflow learning javascript and programming.
I have a problem that i am stuck while learning and thinking any help on this question will be useful for me thanks and the question is:
Example i have a variable a in the code below and i want to convert it to an array in javascript

var a = ["baby,cat,dog"]
i wanted it to be
a = ["baby","cat","dog"].

Somil Garg
  • 474
  • 4
  • 12

2 Answers2

3

Use String.prototype.split() as below

var a = ["baby,cat,dog"];
a = a[0].split(',');
console.log(a);
Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21
  • thank you so much for you valuable time it helped me i was thinking like i already have the , in the array and i if use split it won't work thanks but it did work thanks again – Give me a break internet Nov 18 '19 at 12:27
2

You could take the array and map the splitted values and get a flat array back.

var array = ["baby,cat,dog"];
    result = array.flatMap(s => s.split(','));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392