user8834409
user8834409

Reputation:

Check if a substring exists in an array Javascript

I would like to check if a String exists in my array.

My Javascript Code :

if(Ressource.includes("Gold") === true )
         {
             alert('Gold is in my arrray');
         }

So Ressource is my array and this array contains :

Ressource ["Gold 780","Platin 500"] // I printed it to check if it was true

I don't understand why my test if(Ressource.includes("Gold") === true don't work.

Best regards, I hope someone knows what is wrong with this.

Upvotes: 2

Views: 7998

Answers (4)

user2560539
user2560539

Reputation:

Another approach would be to use Array.prototype.find() and a simple RegExp. That would return the value of the element holding the search term. As said in most answers Array.prototype.includes() works if your search term matches exactly the array element Gold 780.

let Ressource = ["Gold 780","Platin 500"] ;
let found = Ressource.find(function(element) {
let re = new RegExp('Gold');
return element.match(re);
});
console.log(found);
// Working example of Array.prototype.includes()
if(Ressource.includes("Gold 780")) {
  console.log('Gold is in my arrray');
}

Working Fiddle

Upvotes: 0

Brendon Shaw
Brendon Shaw

Reputation: 298

Your problem is that you have a number along with Gold in the string in your array. Try using regex like this:

var Ressource = ["Gold 232331","Iron 123"]

if(checkForGold(Ressource) === true ) {
  console.log('Gold is in my array');
} else {
  console.log('Gold is not in my array');
}

function checkForGold(arr) {
   var regex = /Gold\s(\d+)/;
   return arr.some(x=>{if(x.match(regex))return true});
}  

The MDN docs have a excellent guide to regular expressions. Try this instead.

Upvotes: 0

Anas
Anas

Reputation: 5727

You should loop through your array until you find out if your value exist.

if (Ressource.some(x => x.includes("Gold") === true)) {
    alert('Gold is in my arrray');
}

Upvotes: 0

Bergi
Bergi

Reputation: 664538

The includes array method checks whether the string "Gold" is contained as an item in the array, not whether one of the array items contains the substring. You'd want to use some with the includes string method for that:

Ressources.some(res => res.includes("Gold"))

Upvotes: 5

Related Questions