Mike Mike - 1 month ago 4
jQuery Question

jQuery inArray and Javascript IndexOf returning partial matches. I need to check against a full match

I have an array that contains objects. I am trying to find out if an ID is missing from that array. The code I am using is returning partial matches such as allowing "1" to match "10", "11", "12","13" and so on. This occurs if I iterate as a string or I convert both the search term and the id as a number. For example this code:

var loadUserTemplate = function(json){
var firstArray = json[0];
var parsed = (JSON.parse(firstArray));
var gridStack = $('.grid-stack-item');
var plength = parsed.length;

var gridstackId = Number($(this).attr('data-custom-id'));

for(var j=0; j < plength; j++){
var doesNotContain = Number(parsed[j].id.indexOf(gridstackId));
console.log(typeof doesNotContain);
if(doesNotContain === -1){
console.log(gridstackId + " is not in " + parsed[j].id);

Generates this in the console.log (I am only including the first number, notice how it finds 1 in 10 - 19):

1 is not in 2
1 is not in 3
1 is not in 4
1 is not in 5
1 is not in 6
1 is not in 8
1 is not in 9
1 is not in 20
1 is not in 22
1 is not in 23
1 is not in 24
1 is not in 25
1 is not in 26

I have tried jQuery(inArray) and indexOf with the same results. How do I find full matches, and not partial matches?

Update: parsed is firstArray parsed which is:


gridstackId is the data-custom-id tag of the elements on the DOM.


The value of parsed[j].id is a string, so parsed[j].id.indexOf(gridstackId) checks whether the value of gridstackId is contained in parsed[j].id (the value of gridstackId is converted to a string in the process as well).

If you want to check for equality you should use the comparison operator instead: ===.

Since gridstackId is a number, you have to convert parsed[j].id to a number as well:

Number(parsed[j].id) === gridstackId

Alternatively, do not convert $(this).attr('data-custom-id') to a number, keep it as a string:

var gridstackId = $(this).attr('data-custom-id');
// ...
parsed[j].id === gridstackId;

To solve your problem though, namely checking whether an object with such an ID exists, you can use Array#some:

var gridstackId = $(this).attr('data-custom-id');
var exists = parsed.some(function(obj) {
  return obj.id === gridstackId;

exists will be true if there is at least one object for which the condition (ID equality) is fulfilled.