Reputation: 105
I have a string apple_mango_banana
and an array containing [apple,mango]
.
I want to check if my string contains all of the elements present in the array, if so, I want to show a div with the same ID as my string.
Upvotes: 6
Views: 13191
Reputation: 241
var string="ax_b_c_d";
var array=['b','c','ax','d'];
var arr=string.split("_");
if(array.sort().join("")==arr.sort().join("") && arr.length==array.length)
{
console.log("match");
}
Upvotes: 1
Reputation: 68635
Use every() function on the arr and includes() on the str; Every will return true if the passed function is true for all it's items.
var str = 'apple_mango_banana';
var arr = ['apple','banana'];
var isEvery = arr.every(item => str.includes(item));
console.log(isEvery);
Upvotes: 18
Reputation: 24915
You should use Array.every for such cases.
var s = "apple_mango_banana";
var s1 = "apple_mago_banana";
var fruits = ["apple","mango"];
var allAvailable = fruits.every(function(fruit){
return s.indexOf(fruit)>-1
});
var allAvailable1 = fruits.every(function(fruit){
return s1.indexOf(fruit)>-1
});
console.log(allAvailable)
console.log(allAvailable1)
Upvotes: 2