JQuery specify criteria for finding a value in an array

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)?

    // values
var val1 = { id: 1, description: 'First value'};
var val2 = { id: 2, description: 'Second value'};
var val3 = { id: 3, description: 'Third value'};        
// array of values
var values = [ val1, val2, val3 ];
// inArray of jQuery to know if value is in array -> returns TRUE
var isInArray = $.inArray(val2, values) > -1;

// another instance of same object "val2"
var val2_anotherInstance = { id: 2, description: 'Second value'};
// inArray works as expected -> returns FALSE but desirable result is TRUE
var isInArray_anotherInstance = $.inArray(val2_anotherInstance, values) > -1;

// define function for comparing values (any logic can be implemented, for example searching by Id)
var valueComparer = function(first, second) {
    return first.id == second.id && first.description == second.description;
}
// function compares objects and returns true for different instances
alert(valueComparer(val2, val2_anotherInstance));

// desirable sintax:
// is something like this possible ???      
// NOTE next line not correct
isInArray_anotherInstance = $.inArray(val2_anotherInstance, values, valueComparer) > -1;
// actually what I want is specify criteria for searching value in array
+3
source share
4 answers

Try grep :

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 ];

// another instance of same object "val2"
var val2_anotherInstance = { id: 2, description: 'Second value'};


var items = $.grep(values, function(x) {
    return x.id == val2_anotherInstance.id
})

var found = items.length > 0

For more elegance, you can use the boolean aggregator function as mentioned in this answer :

val2_in_array = $.some(values, function() {
    return this.id == val2_anotherInstance.id
});
+2
source

:

$.fn.inArrayCallback = function(needle, haystack, f) {
  var e = -1;
  $.each(haystack,function(index, value){
      if (f(needle,value)) { e = index; return false; }
    });
  return e;
}

ans = $.fn.inArrayCallback(val2_anotherInstance, values, valueComparer) > -1; 
// returns true

grep , . . .

+1

You can use greep () to filter your array, and then count the number of elements in the created array. But it will process the whole array, and if you have a lot of data, it will not be performance friendly.

0
source

The jquery map function should solve your problem. You can implement your comparison logic in a map callback. reference jQuery map

0
source

All Articles