0

i want to check if a particular string exists in an array of strings. i have an array of strings like below,

const arr = [
    "item-group/1/",
    "item/1/component/2/product/3",
    "item-group/1/item/1/product/5",
    "item/1",

    "item/2",
    "item/2/component/3/products/6",
    "item/2/products/7",
]

i want to check if there is strings matching item/<respective_number> say "item/2" or "item/3" for the products strings with respective item number.

these strings have a meaning

"item-group/1/", //here we have item-group with id 1
    "item/1/component/2/product/3", //here product with id 3 belongs to item with id 
    //1
    "item-group/1/item/1/product/5", //product with id 5 belongs to item with id 1
    "item/1", //item with id 1

     "item/2", //item with id 2
    "item/2/component/3/products/6",//product with id 6 belongs to item with id 2
    "item/2/products/7", //product with id 7 belongs to item with item with id 2

so for these strings i want to check if there is products. if there is strings with products then i want to check if the item they belong to have a string with only item/1 . in other words number after item/ can be anything.

so based on goal above, i filter the strings that contains products/ so i do like below,

const products = arr.filter(a =>
  new RegExp(/products\/([0-9]+)(\/)?$/g).test(a)
);

this will return the strings like below,

"item/1/component/2/product/3",
    "item-group/1/item/1/product/5",

    "item/2/component/3/products/6",
    "item/2/products/7",

now i get the number after item/ with below code

const rex = /\item\/(\d+)\//;
const itemIds = products.map(str => (str.match(rex) ?? [])[1])
  .filter(result => result !== undefined);
     

now the output in itemIds is [1,1,2,2] i remove duplicate values like so

const newItemIds = new Set(itemIds);

now how do i check if arr has strings item/<number_matching_item_id>

so it should look for item/1 and item/2 nothing should follow after these strings.

how can i do that could someone help me with this. thanks.

stackuser
  • 374
  • 2
  • 9
  • Does this answer your question [Check if string ends with](https://stackoverflow.com/questions/38242213/check-if-string-ends-with)? RegExp has `^` that denotes the beginning of the search space, and `$` denotes the end of the search space. Depending on the regexp settings `$` and `^` refer to the whole string to a line. – t.niese Feb 15 '22 at 14:20
  • thanks also how can i stop the checking if more than 2 strings have found – stackuser Feb 15 '22 at 14:22
  • 1
    `how can i stop the checking if more than 2 strings have found` that's a new question. You should do some research and if you don't find a solution ask a new question about that. – t.niese Feb 15 '22 at 14:23

0 Answers0