So, what is required here is an algorithm to achieve the expected result. While multiple answers above have given elegant solutions, the below solutions use a recursive approach.
Solution - Style-1:
const joinUptoLen1 = (arr = [], mlen, i = 0) => (
i < arr.length - 1 ?
arr[i].length + arr[i + 1].length < mlen ?
[
[arr[i], arr[i + 1]]
].concat(joinUptoLen1(arr, mlen, i + 2)) :
[
[arr[i]]
].concat(joinUptoLen1(arr, mlen, i + 1)) :
i === arr.length - 1 ?
[
[arr[i]]
] :
[]
);
The same solution written another way is shown below:
Solution - Style-2:
const joinUptoLen2 = (arr = [], mlen, i = 0) => {
if (i < arr.length - 1) {
if (arr[i].length + arr[i + 1].length < mlen) {
return [
[arr[i], arr[i + 1]]
].concat(joinUptoLen2(arr, mlen, i + 2));
} else {
return [
[arr[i]]
].concat(joinUptoLen2(arr, mlen, i + 1));
}
} else {
if (i === arr.length - 1) return [
[arr[i]]
];
return [];
}
};
Approach is very simple. Check if sum-of-lengths of 2 consequent array-elements is lesser than the input-length. If so, make an array of the 2 elements and push this new-array into the result-array. If not, push an array with just the one element into the result-array. Recursively follow the same and handle the edge-scenario (if the last element was not included into a pair).
And here's a code snippet for quick-demo:
const inpArr1 = ["george", "ben", "bob", "alex", "robert"];
const inpArr2 = ["george", "ben", "bob", "alex", "robert", "pat"];
const splitLen = 10;
const joinUptoLen1 = (arr = [], mlen, i = 0) => (
i < arr.length - 1 ?
arr[i].length + arr[i + 1].length < mlen ? [
[arr[i], arr[i + 1]]
].concat(joinUptoLen1(arr, mlen, i + 2)) : [
[arr[i]]
].concat(joinUptoLen1(arr, mlen, i + 1)) :
i === arr.length - 1 ? [
[arr[i]]
] : []
);
const joinUptoLen2 = (arr = [], mlen, i = 0) => {
if (i < arr.length - 1) {
if (arr[i].length + arr[i + 1].length < mlen) {
return [
[arr[i], arr[i + 1]]
].concat(joinUptoLen2(arr, mlen, i + 2));
} else {
return [
[arr[i]]
].concat(joinUptoLen2(arr, mlen, i + 1));
}
} else {
if (i === arr.length - 1) return [
[arr[i]]
];
return [];
}
};
console.log('style-1 results: ', joinUptoLen1(inpArr1, splitLen));
console.log('style-2 results: ', joinUptoLen2(inpArr1, splitLen));
amount_of_charactersrefers to?