Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
join list elements if their length doesn't exceed a max character limit

so I have a list var be = ["Hello", "welcome", "Hi", "morning", "Hi"] and I want to join the strings if the final string doesn't exceed 12.

so the final result must be a list: ["Hello--welcome", "Hi--morning--Hi"] // I need the -- included

I tried using regex by joining them into one big string and then using .match but didn't work.

EDIT:

this is what I tried:

var s = ["Hello", "welcome", "Hi", "morning", "Hi"].join("--")
var result = s.match(/.{1,12}/g) // ['Hello--welco', 'me--Hi--morn', 'ing--Hi']

thanks

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  • Using Array#reduce, iterate over the array while updating a list of objects with words array and total (total length of words). At each iteration, check if adding the current string to the last added object would exceed a "MAX_LENGTH", if it doesn't update it, otherwise add a new object
  • Using Array#map and Array#join, return the joined list of words

const 
  arr = ["Hello", "welcome", "Hi", "morning", "Hi"],
  MAX_LENGTH = 12;

const res = 
  arr.reduce((list, str) => {
    const last = list[list.length-1];
    if(last && last.total + str.length <= MAX_LENGTH) {
      last.total += str.length;
      last.words.push(str);
    } else {
      list.push({ total: str.length, words: [str] });
    }
    return list;
  }, [])
  .map(({ words }) => words.join('--'));

console.log(res);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda