Skip to content

Instantly share code, notes, and snippets.

@aaronmccall
Created March 24, 2014 23:19
Show Gist options
  • Save aaronmccall/9751450 to your computer and use it in GitHub Desktop.
Save aaronmccall/9751450 to your computer and use it in GitHub Desktop.
Simple implementation of findWhere
// returns first matching list member
function findWhere(list, props) {
var idx = 0;
var len = list.length;
var match = false;
var item, item_k, item_v, prop_k, prop_val;
for (; idx<len; idx++) {
item = list[idx];
for (prop_k in props) {
// If props doesn't own the property, skip it.
if (!props.hasOwnProperty(prop_k)) continue;
// If item doesn't have the property, no match;
if (!item.hasOwnProperty(prop_k)) {
match = false;
break;
}
if (props[prop_k] === item[prop_k]) {
// We have a match…so far.
match = true;
} else {
// No match.
match = false;
// Don't compare more properties.
break;
}
}
// We've iterated all of props' properties, and we still match!
// Return that item!
if (match) return item;
}
// No matches
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment