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

201
Visualizações
Filter array with match regex only returning the first match (javascript)

I have to filter and map an array of strings into another array,the problem is that it only matches the first match and the other string doesnt match it when it should because I have tried the apttern on regex101 and it worked.

I have an object called 'stacks' with multiple variables, for simplicity I only write the one im interested(stackName). "stacks" object:

[
  {
    "stackName": "cc-dev-euw1d-c-1"
  },
  {
    "stackName": "ngi-prd-euw1b-c-3" 
  }
]

I made the following code so I can filter and map this "stacks" object into another array adding a string "none" at the beginning and then filtering it with a regex pattern that looks if the letter at the end before the number is a 'c':

this.oldstacks = ['none', ...stacks
      .filter(stack => stack.stackName.match('c(?=-\d)'))
      .map(stack => stack.stackName)];

For example these string should match:

cc-dev-agw1d-c-1
dd-prd-agw1b-c-3

But these one dont match, because they dont have a "c" before the number:

dd-prd-agw1b-d-3
dd-prd-agw1b-r-3

I would like to filter the stacks object into the oldStacks objects so it only takes the string that match the patter but I cant seem to find out how because this way it only takes the first match and I would like all the matches of the stacks.

Thanks

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The issue is that match takes a regex instead of a string, and you can use a match only instead of the lookahead assertion.

const stacks = [{
    "stackName": "cc-dev-euw1d-c-1"
  },
  {
    "stackName": "ngi-prd-euw1b-c-3"
  }
];

const oldstacks = ['none', ...stacks
  .filter(stack => stack.stackName.match(/c-\d/))
  .map(stack => stack.stackName)
];

console.log(oldstacks);

Instead of first filtering and then map, you might also use reduce:

const stacks = [{
    "stackName": "cc-dev-euw1d-c-1"
  },
  {
    "stackName": "ngi-prd-euw1b-c-3"
  }
];

const oldstacks = ['none', ...stacks
  .reduce((acc, curr) => {
    if (/c-\d/.test(curr.stackName)) acc.push((curr.stackName))
    return acc;
  }, [])
];

console.log(oldstacks);

about 4 years ago · Santiago Trujillo 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