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
  • 129
  • 1
  • 3
  • 12

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
  • 25,448
  • 4
  • 17
  • 37
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
  • 263,463
  • 30
  • 215
  • 251