-1

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?

job seeker
  • 53
  • 9
  • Can you add some more example inputs and expected outputs? I don't see why you wouldn't want `"123".includes(targetString)` to be `true` based on the description of the problem. Is your condition just `targetString === "1"`? – Ryan Pattillo Jul 19 '22 at 03:52
  • Yes, Ryan. for string I need to check stringA === targetString but for array i need to check whether arr has stargetString using arr.includes(targetString). but i want to do these two check in one goal. The way I am using(includes method)will make some mistake when stringA is "123". As it will also return true "123".includes(targetString). Hope it makes sense to you – job seeker Jul 19 '22 at 03:55
  • use an && condition ? – cmgchess Jul 19 '22 at 04:01

1 Answers1

2

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
Ryan Pattillo
  • 331
  • 1
  • 8