Skip to content Skip to sidebar Skip to footer

Check For Element In Array

I'm trying to check if an elements already exists in an array. I know of at least 2 different ways to do so: [1] and [2]. I tested both of them, but get no in both cases: var myAr

Solution 1:

Both of those are doing the almost the same thing: Checking if myArray has a property called "Banana", which it doesn't; it has keys 0,1,2, and 3, and the value at myArray[0] happens to be "Banana".

If you want to check if a string is in an array you can use Array.prototype.indexOf:

if( myArray.indexOf("Banana") >= 0 ) {
  console.log("yes")
} else {
  console.log("no")
}

Solution 2:

You are, in both cases, looking for the bananath (+1) element of the array, which is not correct.

Either way, the first one should not be used (even if it served to this purpose) because it is not intended to be used with arrays, since it will look for properties.

Post a Comment for "Check For Element In Array"