I have been doing tons of Ajax recently and work with lots of my domain objects converted their JavaScript counterparts. I found myself writing several functions that looped through the arrays of objects to search by property values. I decided to write a simple jQuery plugin that would allow me to search an array of primitive or complex types.
Note: This is my first attempt at writing a jQuery plugin. I'm not sure if i went about it the correct way. My main concern is efficiency and cross-browser support of the search logic.
Thanks!
Code to critique:
$(function() {
$.indexOfArray = function (search, array) {
var keys = [];
var index = -1;
var primitiveType = true;
for (var propertyName in search) {
primitiveType = false;
keys.push(propertyName);
}
if ($.isArray(array)) {
for (var a = 0; a < array.length; a++) {
var match = 0;
if (primitiveType && array[a] == search) {
index = a;
break;
}
else if (!primitiveType) {
for (var b = 0; b < keys.length; b++) {
if (search[keys[b]] == array[a][keys[b]]) {
match++;
}
}
if (match == keys.length) {
index = a;
break;
}
}
}
}
return index;
}
});
Simple example of use (It also works with primitive type arrays such as strings or ints):
var testArray = [{Id:1, FirstName: 'John'}, {Id:2, FirstName: 'Jake'}, {Id:2, FirstName: 'Jason'}];
var selectedPerson = testArray[$.indexOfArray({Id:2}, testArray)];