Home > Software design >  How we can check arr and stringA are satisfied with targetString in one goal?
How we can check arr and stringA are satisfied with targetString in one goal?

Time:07-19

I have a scenario to check whether the array or a string includes one specific string.

For example, we have a returned variable which can be an array or a string. Then we need to check when it is array, it includes targetString, when it is a string, it equals to targetString

const returnedVariable = ['1', '2', '3'] or "1";

const targetString = "1"

May I please know how we can check this in one goal?

CodePudding user response:

There isn't a single method that has this behavior. You could make your own function to do it though. typeof can be used to tell whether you're checking a string; you could also use Array.isArray to tell if you're checking an Array.

function isOneOrHasOne(thingToCheck, targetString) {
    if (typeof thingToCheck === "string") {
        return thingToCheck === targetString;
    }
    
    return thingToCheck.includes(targetString);
}

console.log(isOneOrHasOne(["1", "2", "3"], "1")); // true
console.log(isOneOrHasOne("1", "1"));             // true
console.log(isOneOrHasOne("123", "1"));           // false

  • Related