Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!