1

my goal is to check if any -data (data-id) on site have same value as one of elements in array but inArray always returns -1

 <a href="#" data-id="2">
 <a href="#" data-id="3">

<script>
var arrayObjects = <?php echo $json_array; ?>;
console.log(arrayObjects);

$("[data-id]").each(function(){
    var data_id = $(this).data('id');

    if(jQuery.inArray(data_id, arrayObjects) > -1) { // f
        console.log(data_id);
        console.log('found');
    } else { // nf
        console.log(data_id);
        console.log('not found');
    }
});

From my console:

["2", "3"]
3
not found
2
not found

1 Answer 1

1

When you retrieve the data-id var data_id = $(this).data("id"), you get a Number, whereas the arrayObjects contains Strings !

Here, check this JSfiddle you'll see that the console.log(typeof(data_id)) is Number. To get this work, just add ""+ to force the data_id to be a String :

jQuery.inArray(""+data_id, arrayObjects)

Update:

As @barmar pointed out, var data_id = $(this).attr('data-id') fits better as the .attr() method will return a string, .data() parse the data as JSON, giving a number in our case.

No more trick forcing the type to string

jQuery.inArray(data_id, arrayObjects)

Sign up to request clarification or add additional context in comments.

3 Comments

I'm glad it helped :) Please consider putting the answer as Accepted for other readers !
FYI, the reason this happens is because .data() parses the data as JSON. If you use .attr('data-id') you'll get a string.
That's a good point , i changed to attr for a sake of neatness

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.