user1234
user1234

Reputation: 3159

Evaluate for multiple checks for items in an array

I have 3 values whose value is to be compared to a key, like:

array=["test", "test1", "test2"];
array.find((ele)=>{
        return (ele === "test" || ele === "test1" || ele === "test2");
      });

I'm already doing this, however I wanted to check if there is better way to do this? I tried:

if (["test", "test1", "test2"].every(function(x){
     {return true;}
    }))

this does not work, any ideas?

Upvotes: 2

Views: 77

Answers (3)

Unmitigated
Unmitigated

Reputation: 89224

You can use Array#some with Array#includes to check if the first array contains any of the elements in the second.

array=["test", "test1", "test2"];
if (["test", "test1", "test2"].some(x=>array.includes(x))){
  console.log("true");
}

Upvotes: 0

Victor Gazzinelli
Victor Gazzinelli

Reputation: 91

How about using startsWith() ?

let array = ["test","test1","test2"];
array.forEach(key => console.log(key.startsWith("test")));

Upvotes: 1

Always Helping
Always Helping

Reputation: 14570

You could use Array#Includes to check to check if you array has strings you are looking for!

Demo:

let arr = ["test", "test1", "test2"];
if(arr.includes("test") || arr.includes("tes1") || arr.includes("test2")) {
  console.log(true);
}

You could also use ArrayMap and startswith function to look for strings that matches the required condition.

Demo:

let arr = ["test", "test1", "test2"];

let checkArr = arr.map(x => x.startsWith('test')).join(',')
console.log(checkArr)

Upvotes: 1

Related Questions