Leo Messi
Leo Messi

Reputation: 6186

Better way to check if a string has a value from a list of strings

There is a list of strings and I want to check if the one I check has a value from there.

For example, the list is "good", "amazing", "bad", "better", "worse"

and this function:

checkPositive = (str) => {
  if(str === "good" || str === "amazing" || str === "better") {
      return true;
    }
  return false;
}

My question is if it's possible to do it more efficiently than it is now, I don't like how that if statement looks.

Upvotes: 0

Views: 41

Answers (4)

Narendra Jadhav
Narendra Jadhav

Reputation: 10262

You could also use Regular_Expressions as well to check the particular string

const checkPositive = str => /good|amazing|better/.test(str.toLowerCase());

console.log(`For bad ` +checkPositive('bad'));
console.log(`For amazing `+checkPositive('amazing'));

Upvotes: 0

brk
brk

Reputation: 50326

You can use indexOf which will return -1 is the string is not present in list(assuming it is an array)

const strList = ["good", "amazing", "bad", "better", "worse"]

checkPositive = (str) => {
  return strList.indexOf(str) !== -1 ? true : false;
}

console.log(checkPositive('good')) // true;
console.log(checkPositive('hello')) // true;

Upvotes: 0

collapsar
collapsar

Reputation: 17238

Build a dictionary:

let dict={
        good:  true
      , amazing: true
      , better: true
    };

checkPositive = str => { return dict[str]; } // dict[str] ? true : false, if you need actual boolean values 

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371019

You could use an array and .includes:

checkPositive = str => ['good', 'amazing', 'better'].includes(str)

Upvotes: 2

Related Questions