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?
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)
How about using startsWith()
?
let array = ["test","test1","test2"]; array.forEach(key => console.log(key.startsWith("test")));
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"); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.