Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
Split array of strings into more arrays of strings?

Hello so what I want to do is split array of names into more arrays of names and each arrays element joined together should be smaller than specific amount of characters and none of the strings should be split in half. if it needs to be split in half then move it to the next array. so an example would be.

Input: arr: ["george","ben","bob","alex","robert"] amount_of_characters: 10

Output: [["george","ben"],["bob","alex"],["robert"]]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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);

about 4 years ago · Juan Pablo Isaza Relatório

0

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;

};

about 4 years ago · Juan Pablo Isaza Relatório

0

Another way of writing it using 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));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda