0

I have a array in javascript

var arr = ["12","22","33","42"];
  1. If I search for 1 it should not match because it is not a complete array element.
  2. If I search for 12 it should match because it is a complete array element.

I have searched web for this but found

var match = arr.indexOf('1');

But this does not solve my problem

Anybody can help?

Anurag Jain
  • 194
  • 9
  • 5
    It looks like indexOf seems exactly what you need. Maybe you can elaborate on why it doesn't solve the problem? – Felix Kling May 10 '14 at 05:24
  • indexOf should work. So if it doesn't work I would suggest posting your code. And remember that indexOf returns -1 if not found. You can read about indexOf here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – WizKid May 10 '14 at 05:25
  • +1 to Felix -- also, just to be clear indexOf returns -1 when there is no match. – jtmoulia May 10 '14 at 05:26
  • If indexOf doesn't work, then either you're doing something wrong or you're not phrasing your question correctly – Meredith May 10 '14 at 05:26
  • If you want a boolean return value, check the return value of indexOf("1") for example. If it returns -1, return false, if it returns a value greater than -1, return true – blueygh2 May 10 '14 at 05:27

3 Answers3

0

So indexOf returns the position the element you are searching for is at. If no element is found, it returns -1. This is the way you can check it.

var arr = ["12","22","33","42"];
var match = arr.indexOf("12");
if(match > -1) {
    // Found match, at position "match"
    var element = arr[match]; // = "12"
} else {
    // Element not in array
}
ReGdYN
  • 536
  • 2
  • 7
0

Try This:

var a = ["12","22","33","42"];
if(a.indexOf('12')!= '-1')
{
    alert("success")
}
else
{
    alert("failure")
}
anusha
  • 2,087
  • 19
  • 31
0

please refer this, I think this will help you,
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.
so try this.
$.inArray(1,arr) > -1

Sanjay
  • 1,958
  • 2
  • 17
  • 25