Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery inArray is always returning -1

Tags:

jquery

I cannot figure out why I keep getting -1 for lastProductIndex when clearly the lastProductID is in the array!

var lastProductID = 6758;
var allProductIDs = [5410, 8362, 6638, 6758, 7795, 5775, 1004, 1008, 1013]
var lastProductIndex = $.inArray(lastProductID, allProductIDs);
like image 610
PositiveGuy Avatar asked Jul 01 '09 21:07

PositiveGuy


2 Answers

I had the same problem yesterday,,

var data=[2,4,6,8];
alert( $.inArray(4,data) ) // output 1 as expected
alert( $.inArray("4",data) ) // output -1 as expected 

Generally this occurs when you get the value to check from a input element or something that returns a string. You need to do parseInt(string,radix) to convert it to a number...

like image 107
AgelessEssence Avatar answered Sep 28 '22 17:09

AgelessEssence


Try this instead:

$.grep(allProductIDs, function(n) { return n == lastProductID; });

Caveat: grep returns an array.

It looks like jQuery does an === instead of == with inArray.

like image 39
Joe Chung Avatar answered Sep 28 '22 18:09

Joe Chung