Hola, lo que quiero hacer es dividir la matriz de nombres en más matrices de nombres y cada elemento de la matriz unido debe ser más pequeño que la cantidad específica de caracteres y ninguna de las cadenas debe dividirse por la mitad. si necesita dividirse por la mitad, muévalo a la siguiente matriz. asi que un ejemplo seria.
Input: arr: ["george","ben","bob","alex","robert"] amount_of_characters: 10 Output: [["george","ben"],["bob","alex"],["robert"]] const arr = ["george","ben","bob","alex","robert"]; const amount_of_characters = 10; const result = []; let sumChars = 0; for (let i = 0; i < arr.length; i++) { const word = arr[i]; if (word.length + sumChars > amount_of_characters) { result.push([word]) sumChars = 0; } else { !result.length ? result.push([word]) : result[result.length - 1].push(word); } sumChars += word.length; }; console.log(result);const foo = function (arr, max) { // arr - input, max - max characters in one array const result = []; for (let i = 0; i < arr.length; i++) { let cur = []; if (arr[i].length < max && i !== arr.length - 1) { let sum = arr[i].length; cur.push(arr[i]); while (sum <= max) { i++; if (arr[i].length + sum <= max) { sum += arr[i].length; cur.push(arr[i]); } else { sum = max + 1; i--; } } } else cur.push(arr[i]); result.push(cur); } return result;};
Otra forma de escribirlo usando Array.reduce():
const input = ["george","ben","bob","alex","Robert"]; let idx=0; const output = (amount_of_characters)=>{ return input.reduce((acc,curr)=>{ acc[idx]?null: acc.push([]); acc[idx].join('').length + curr.length <= amount_of_characters? acc[idx].push(curr):(idx++, acc.push([]), acc[idx].push(curr)); return acc; },[]) } console.log(output(10));