In javascript, I need to know if an array contains a value. Values are objects, and I can have different instances of the same object, which means $ .inArray (...) will not work. I know how to accomplish my task with $ .each (...), and my question is: is it possible to pass a function with the logic of comparing values to any of jQuery methods (see Sample with the right sintax)?
var val1 = { id: 1, description: 'First value'};
var val2 = { id: 2, description: 'Second value'};
var val3 = { id: 3, description: 'Third value'};
var values = [ val1, val2, val3 ];
var isInArray = $.inArray(val2, values) > -1;
var val2_anotherInstance = { id: 2, description: 'Second value'};
var isInArray_anotherInstance = $.inArray(val2_anotherInstance, values) > -1;
var valueComparer = function(first, second) {
return first.id == second.id && first.description == second.description;
}
alert(valueComparer(val2, val2_anotherInstance));
isInArray_anotherInstance = $.inArray(val2_anotherInstance, values, valueComparer) > -1;
source
share