TheRealPapa TheRealPapa - 3 months ago 49
jQuery Question

Convert string to array - jQuery.inArray() not working

I have a string that looks like this (this is a value I get from an input in the page's HTML):

'[123,234,345]'


I turn this value into an array in my JS:

var tempProjectTasks = $('#task_id_array').val();
tempProjectTasks = tempProjectTasks.replace('[', '').replace(']','');
selectedProjectTasks = tempProjectTasks.split(',');


I then compare this array in a loop

$.each(tasks, function(key, value) {
if ($.inArray(value['id'], selectedProjectTasks) != -1) {
checked = 'checked';
} else {
checked = '';
}
... more stuff here ...
});


This is building a list for the HTML and each row contains a checkbox.

I can see in the console the comparison for these values being
-1
by adding the
console.log
commands below inside the loop.

console.log(selectedProjectTasks);
console.log(value['id']);
console.log($.inArray(value['id'], selectedProjectTasks));


In the console:

["123","234","345"]
123
-1


Why is the
inArray()
not finding the matching values? What have I missed? Thanks

Answer

["123","234","345"] is an array of string, where as 123 is an integer.

You can convert this to string using toString before searching it in array

console.log($.inArray((value['id'].toString(), selectedProjectTasks));
Comments