Skip to content

Instantly share code, notes, and snippets.

@jimmysawczuk
Created January 17, 2012 21:42
Show Gist options
  • Save jimmysawczuk/1629109 to your computer and use it in GitHub Desktop.
Save jimmysawczuk/1629109 to your computer and use it in GitHub Desktop.
find object in array search engine
<script type="text/javascript">
function findInArray(needle, haystack)
{
function isMatch(needle, haystack)
{
if (haystack == needle)
{
return true;
}
else if (typeof needle == 'object' && typeof haystack == 'object')
{
var match = true;
for (var i in needle)
{
match = match && haystack.indexOf(needle[i]) >= 0;
}
return match;
}
else if (typeof haystack == 'object')
{
if (haystack.indexOf(needle) >= 0)
{
return true;
}
else
{
return false;
}
}
return false;
}
var idx = false;
var matches = [];
var match = true;
for (var i in haystack)
{
val = haystack[i];
match = true;
for (var key in needle)
{
if (typeof val[key] == 'undefined')
{
match = false;
break;
}
match = match && isMatch(needle[key], val[key]);
if (!match)
{
break;
}
}
if (match)
{
matches.push({'idx': i, 'val': val});
}
}
return matches;
}
function search(params)
{
console.debug(JSON.stringify(params), findInArray(params, haystack));
}
var haystack = [
{'id': 1, 'name': 'Jimmy', 'sports': ['baseball','football']},
{'id': 2, 'name': 'Jim', 'sports': 'football'},
{'id': 3, 'name': 'Bryan', 'sports': 'soccer'},
{'id': 4, 'name': 'Bobby'},
{'id': 5, 'name': 'Dan', 'sports': 'soccer'}
];
search({'id': 2}, haystack);
search({'name': 'Jim'});
search({'sport': 'soccer'}, haystack);
search({'sports': ['baseball','football']}, haystack);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment