0

I have an array converted from string using JSON.parse:

 list = "625, 632";    
 list = JSON.parse("["+items_string+"]");

which contains:

 Array [ 625, 632 ]

Trying to find a given item in the array JQuery inArray will always return -1

 if(jQuery.inArray('625', list) > -1){
     //never get here
 }

 console.log(jQuery.inArray('625', list));
 //will print -1

Does anyone knows why?

Adry
  • 307
  • 1
  • 4
  • 21
  • 3
    Possible duplicate of [jQuery.inArray(), how to use it right?](https://stackoverflow.com/questions/18867599/jquery-inarray-how-to-use-it-right) – Alfabravo Oct 23 '17 at 16:44
  • 1
    Documentation says 'The comparison between values is strict'. Maybe searching for a number will yield the expected result. – Alfabravo Oct 23 '17 at 16:46
  • console.log(jQuery.inArray(625, list)); try to find int, not string – Aliaga Aliyev Oct 23 '17 at 16:46
  • 1
    You are comparing a string to a number, that's why you get always `-1`. – Ervin Szilagyi Oct 23 '17 at 16:47
  • @Alfabravo I've read that question before, I know inArray is search for the index, and won't output a boolean, still I didn't know what I was missing. – Adry Oct 23 '17 at 18:59

2 Answers2

1

Pass a number instead of a string

$.inArray(625, [ 625, 632 ]) // `0`
guest271314
  • 1
  • 15
  • 104
  • 177
0
var list = new Array(625, 632);
if( $.inArray(625, list) !== -1 ) {    
    alert("found");
}
lrnzcig
  • 3,868
  • 4
  • 36
  • 50
jvk
  • 2,133
  • 3
  • 19
  • 28