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

125
Vistas
Divide an array into subarray depending on string and join its items. Javascript

I would like to transform an array into another separing its items depending on a string data, and, when there are two or more items together and none of them is is the limit string data i would like to join then by "/". Something like this:

const stringLimit = "aa"; let arrayData =["b","c","aa","aa","d","c","aa","f"];

result:

arrayResult=["b/c","d/c","f];

I have try this, however, I think that there should be a better way

let stringItem;
let totalRouteDevice = new Array();
for (let index = 0; index < arrayData.length; index++) {
    const item = arrayData [index];
    if(item!=='aa' && item !== 'bb') {
      stringItem = stringItem!=""?`${stringItem}/${item}`:stringItem
    } else if(stringRouteItem!=="") {
      totalRoute.push(stringItem);
      stringItem ="";
    }
}

I have try this, however, I think that there should be a better way

let stringItem;
let totalRouteDevice = new Array();
for (let index = 0; index < arrayData.length; index++) {
    const item = arrayData [index];
    if(item!=='aa' && item !== 'bb') {
      stringItem = stringItem!=""?`${stringItem}/${item}`:stringItem
    } else if(stringRouteItem!=="") {
      totalRoute.push(stringItem);
      stringItem ="";
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Not saying this is better but you could group your data using reduce, splitting it by stringLimit, and then joining the groups by / as follows:

const stringLimit = 'aa'

const arrayData = ["b","c","aa","aa","d","c","aa","f"]

let arr = []

arrayData.reduce((acc, item, i) => {
  if (item !== stringLimit) {
    acc.push(item)
  } else {
    if (acc.length) {
      arr.push(acc)
    }
    acc = []
  }

  if (item !== stringLimit && i === arrayData.length - 1) {
    arr.push(acc)
  }

  return acc
}, [])

let result = arr.map((i) => i.join('/'))

console.log(result)

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