How to join elements of a string array into larger strings joined by spaces to a certain length

I have an array of strings in which I would like to join them by spaces, however I don’t want to go over X length for each “chunk”.

For example:

let userList = ["Bill", "Tom", "Micheal", "Steve", "Aa", "Bb", ...] // array of strings i want to "chunk"

// chunkArr(ArrayOfStrings, LengthOfEachChunk)
chunkArr(userList, 10) // -> ["Bill Tom", "Micheal", "Steve Aa", "Bb"] // Each string in the new array has a length less than the LengthOfEachChunk

How could I do this?

Answer

One way is to use reduce for this:

function chunkArr(arr, len) {
    return arr.reduce((acc, word, i) => {
        if (!i || acc[acc.length-1].length + word.length >= len) {
            acc.push(word);
        } else {
            acc[acc.length - 1] += " " + word;
        }
        return acc;
    }, []);
}


let userList = ["Bill", "Tom", "Micheal", "Steve", "Aa", "Bb"];
let result = chunkArr(userList, 10) 
console.log(result);