1

What is the best way to convert:

const a = ["jan,feb,may", "apr,may,sept,oct", "nov,jan,mar", "dec", "oct,feb,jan"]

to

const res = ["jan","feb","may","apr","may","sept","oct","nov","jan","mar","dec","oct","feb","jan"]

PS: in javascript, I tried using array.reduce() and split method. but that didn't work. here is what I tried

let flat = arr.reduce((arr, item) => [...arr, ...item.split(',')]);
ajay
  • 328
  • 1
  • 5
  • 17

2 Answers2

2

Using Array#flatMap and String#split:

const a = ["jan,feb,may", "apr,may,sept,oct", "nov,jan,mar", "dec", "oct,feb,jan"];

const res = a.flatMap(e => e.split(','));

console.log(res);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1

In this case you could just join and split again:

const a = ["jan,feb,may", "apr,may,sept,oct", "nov,jan,mar", "dec", "oct,feb,jan"];

const res = a.join().split(',');

console.log(res);

Or implicitly joining:

const a = ["jan,feb,may", "apr,may,sept,oct", "nov,jan,mar", "dec", "oct,feb,jan"];

const res = "".split.call(a, ",");

console.log(res);

Or implicitly joining when splitting with a regex method:

const a = ["jan,feb,may", "apr,may,sept,oct", "nov,jan,mar", "dec", "oct,feb,jan"];

const res = /,/[Symbol.split](a);

console.log(res);
trincot
  • 317,000
  • 35
  • 244
  • 286