I want to convert all elements with commas to multiple elements in an array in JS.
["el1,el2", "el3"] => ["el1", "el2", "el3"]
How can I do this?
I want to convert all elements with commas to multiple elements in an array in JS.
["el1,el2", "el3"] => ["el1", "el2", "el3"]
How can I do this?
Use flatMap
with split
:
const result = ["el1,el2", "el3"].flatMap(s => s.split(","));
console.log(result);
Alternatively, first join to one string:
const result = ["el1,el2", "el3"].join().split(",");
console.log(result);
flatMap
can cycle through every item, change it and flatten elements into one array
["el1,el2", "el3"].flatMap(v =>
v.includes(',') // check if element includes ','
? v.split(',') // if true - split it into smaller arrays
: v // if false - just return the string as it was
)