6

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.

asked Nov 17, 2016 at 8:10
3
  • 1
    please add your try and have a look here: minimal reproducible example. Commented Nov 17, 2016 at 8: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. Commented Nov 17, 2016 at 8: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 :- stackoverflow.com/questions/14130104/… Commented Nov 17, 2016 at 8:17

3 Answers 3

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);

answered Nov 17, 2016 at 8:15

2 Comments

ie wont support, supports start from edge 14
includes and every are ES6 features
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)

answered Nov 17, 2016 at 8:14

Comments

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");
 }
answered Nov 17, 2016 at 8:25

1 Comment

This will not work if order is changed. Like "banana_apple"

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.