Home > Software engineering >  Filter array with match regex only returning the first match (javascript)
Filter array with match regex only returning the first match (javascript)

Time:07-25

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

CodePudding user response:

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

  • Related