Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

81
Views
Array some(). How can I find the index of the true match found?

I've created the example below to illustrate what I'm trying to do. Essentially I wanted to get the array index of the true match and return a custom response based on which end point regex was matched.

Is this possible with array some()? Or is there a different method?

// Simulate an http request
const reqUrl = "http://127.0.0.1/app/api/v1/customers/999999";

// Parse the parts of a url
const url = new URL(reqUrl);

// Get url pathname and Decode it, if encoded
const urlPathNameDecoded = decodeURIComponent(url.pathname);

/* /app/api/v1/customers/999999 */
console.log(urlPathNameDecoded);

// Create list of regular expressions to match against url pathname decoded
const regexList = [
  /apple/,
  /^\/app\/api\/v1\/customers\/([1-9]{1}[0-9]{0,8})\/?$/, // Match -> /app/api/v1/customers/999999
  /orange/,
  /^\/app\/api\/v1\/projects\/([1-9]{1}[0-9]{0,8})\/?$/, //  Match -> /app/api/v1/projects/999999
  /pear/,
  /^\/app\/api\/v1\/vendors\/([1-9]{1}[0-9]{0,8})\/?$/, //   Match -> /app/api/v1/vendors/999999
  /strawberry/,
];

// Test if at least one element in the array passes the test implemented by the provided function
const isMatch = regexList.some(regex => regex.exec(urlPathNameDecoded));

console.log("isMatch:", isMatch);

8 months ago ยท Juan Pablo Isaza
Answer question
Find remote jobs