-3

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?

Shahriar
  • 1,855
  • 2
  • 21
  • 45
  • 2
    Why do you need the "shortest" way to do it, as opposed to the "most maintainable" or "fastest", or just "working"? Because we have sites for [codegolf.se]... – Heretic Monkey Jul 06 '22 at 22:01

2 Answers2

2

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);
trincot
  • 317,000
  • 35
  • 244
  • 286
0

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
)
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 1
    Why bother with the conditional? – Barmar Jul 06 '22 at 22:02
  • For some reason I thought that split would return two items if it doesn't find anything to split. Also minor performance improvement, but the other answer is better – Konrad Jul 06 '22 at 22:06
  • 1
    There is an edge case: an empty string will be split into an array with a single element, not an empty array. Maybe that's what you're thinking of. – Barmar Jul 06 '22 at 22:08
  • Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. – Saeed Zhiany Jul 07 '22 at 07:56
  • "if you explain how this code is different from the code in the question" there is literally no code in the question. – Konrad Jul 07 '22 at 08:15