Some method on array


function telephoneCheck(str) {

  const validPatterns=[

    /^\d{3}-\d{3}-\d{4}$/,

    /^\(\d{3}\)\d{3}-\d{4}$/,

    /^1 \d{3}-\d{3}-\d{4}$/,

    /^1 \(\d{3}\) \d{3}-\d{4}$/,

    /^\d{10}$/,

    /^1\(\d{3}\)\d{3}-\d{4}$/,

    /^1 \d{3} \d{3} \d{4}$/

    

  ]

  return validPatterns.some((pattern) => pattern.test(str));

}

telephoneCheck("555-555-5555");

I am not understanding the argument passed in some method, what is pattern? I get that some() is going to return a boolean value. Can someone please explain.

(pattern) => pattern.test(str) is the callback function you are passing into some(). pattern is just the name you have given to the first argument that is automatically passed into the callback function (you could have called it anything, but I think pattern makes sense here). Seeing as validPatterns is an array of JS patterns and you are calling the first argument pattern, what do you think pattern is?

2 Likes

Adding to what @bbsmooth said, that argument will represent any element in an array. The method .some() will check if at least any or “some” element from the array satisfies certain condition.

For example:
Let’s say we have an array of numbers, called nums like this: [2,3,5,6] and we want to test if there is an element above 3; then we can do it using the method as shown below:

nums.some(n => n > 3)

It will return true because the array contains one or more elements that satisfies that condition. Hence, you can name the argument to whatever you want and it will always takes into account the element.

2 Likes

Thanks a lot!! Now I understood what pattern indicates here, it represents the patterns given in the array.

Thank you so much!! I got it now. The example you mentioned made it easy to understand.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.