Created
February 19, 2016 16:46
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 }].