2

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?

Always Helping
  • 14,316
  • 4
  • 13
  • 29
user1234
  • 3,000
  • 4
  • 50
  • 102
  • 1
    Does this answer your question? [Simplest code for array intersection in javascript](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) – Robo Robok Aug 11 '20 at 01:50
  • Are you trying to determine if all items in an array match a set of criteria or return the first item in an array that matches a set of criteria? – Rylee Aug 11 '20 at 02:00
  • @RoboRobok; somewhat, but not completely, however it helped me for other usecase, thanks for pointing it out – user1234 Aug 11 '20 at 02:59

3 Answers3

1

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)
Always Helping
  • 14,316
  • 4
  • 13
  • 29
1

How about using startsWith() ?

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

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");
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80