DarV
DarV

Reputation: 37

jQuery - Checking if -data element exist in array with each() and inArray()

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

Upvotes: 1

Views: 1091

Answers (1)

Gregoire
Gregoire

Reputation: 767

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)

Upvotes: 1

Related Questions