JavaScript: Divide array elements on space and add to same list

Viewed 139

In JavaScript, let's say I have an array like this: ["Foo", "Bar", "Baz Foo"] and want to convert it into this: ["Foo", "Bar", "Baz", "Foo"].

In other words, split the array on space and add it as an extra element to the array. I feel like it should be some simple solution to this, but I just don't get it right. Does anyone know how I can achieve this ?

1 Answers

You can use Array#flatMap along with String#split.

const arr = ["Foo", "Bar", "Baz Foo"];
const res = arr.flatMap(x => x.split(" "));
console.log(res);

You could also use Array#join to produce a string and then use String#split.

const arr = ["Foo", "Bar", "Baz Foo"];
const res = arr.join(' ').split(' ');
console.log(res);

Related