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

197
Vistas
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 Respuestas
Responde la pregunta

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