2

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(',')]);
0

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.