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

124
Visualizações
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 Respostas
Responde à pergunta

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