Skip to content

Instantly share code, notes, and snippets.

@sedera-tax
Created February 19, 2016 16:46
Show Gist options
  • Save sedera-tax/0184a068e8011b4fced1 to your computer and use it in GitHub Desktop.
Save sedera-tax/0184a068e8011b4fced1 to your computer and use it in GitHub Desktop.
Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching property and value pairs (second argument). Each property and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.
function where(collection, source) {
var arr = [];
// What's in a name?
var n=0;
var l = Object.keys(source);
var nb = l.length;
for(var j in collection){
var res = 0;
for (var i in source) {
if (source.hasOwnProperty(i)) {
var valeur = source[i];
var s = new Object();
var d = collection[j].hasOwnProperty(i);
for(var k in collection[j]){
if(k === i){
if(collection[j][k] === valeur){
res++;
if(res === nb){
s = collection[j];
arr[n] = s;
n++;
}
}
}
}
}
}
}
return arr;
}
where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 });
where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
@sedera-tax
Copy link
Author

where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }) should return [{ first: "Tybalt", last: "Capulet" }].
where([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }], { "a": 1 }) should return [{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }].
where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }) should return [{ "a": 1, "b": 2 }, { "a": 1, "b": 2, "c": 2 }].
where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "c": 2 }) should return [{ "a": 1, "b": 2, "c": 2 }].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment