Since there are already working answers here, I will share my recursive approach. But in the future, please share the work you've done yourself. If you haven't been able to code anything, then share some of your thought-processes.
Here we build this atop a reusable function, chunk
that splits any array into equal-sized chunks, plus a possibly smaller final chunk. Our chunkWords
function splits a string at white space, then runs chunk
on the result.
const chunk = (n) => (xs) =>
xs .length <= n ? [xs] : [xs .slice (0, n), ... chunk (n) (xs .slice (n))]
const chunkWords = (n) => (s) =>
chunk (n) (s .split (/\s+/)) // .map (ss => ss .join (' '))
console .log (
chunkWords (3) ('Now is the time for all good men to come to the aid of their party')
)
If you want the result to be turned back into strings, just uncomment the .map
call in chunkWords
. That would yield ["Now is the", "time for all", "good men to", "come to the", "aid of their", "party"]
.