5

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.

Lloyd Nicholson
  • 474
  • 3
  • 12
Kritika
  • 95
  • 1
  • 1
  • 9
  • 1
    please add your try and have a look here: [mcve]. – Nina Scholz Nov 17 '16 at 08:11
  • 1
    post your code of what you have tried so far, what went wrong and what is the part that you need help with, SO isn't an code fabric that produces code for you. – Kevin Kloet Nov 17 '16 at 08:13
  • Use split function to split your string in "_" .This will create a new array and then just check if your array is a subset of this new array. This is how you check if an array is a subset of another array :- http://stackoverflow.com/questions/14130104/how-do-i-test-if-one-array-is-a-subset-of-another – Ezio Nov 17 '16 at 08:17

3 Answers3

18

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);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
2

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)
Rajesh
  • 24,354
  • 5
  • 48
  • 79
1
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");
 }
Soham Bhaumik
  • 211
  • 2
  • 15