Skip to content

Instantly share code, notes, and snippets.

@SerhiiLihus
Created December 25, 2015 07:55
Show Gist options
  • Save SerhiiLihus/9b5f32b1f5e1cfd06c41 to your computer and use it in GitHub Desktop.
Save SerhiiLihus/9b5f32b1f5e1cfd06c41 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).
// Bonfire: Where art thou
// Author: @serhiilihus
// Challenge: http://www.freecodecamp.com/challenges/bonfire-where-art-thou#?solution=function%20where(collection%2C%20source)%20%7B%0A%20%20var%20arr%20%3D%20%5B%5D%2C%20count%3B%0A%20%20var%20sourceObject%20%3D%20Object.keys(source)%3B%0A%20%20for%20(%20var%20i%20%3D%200%3B%20i%20%3C%20collection.length%20%3B%20i%2B%2B)%20%7B%0A%20%20%09count%20%3D%200%3B%0A%20%20%20%20for%20(%20var%20j%20%3D%200%3B%20j%20%3C%20sourceObject.length%20%3B%20j%2B%2B)%0A%20%20%20%20%20%20if%20(collection%5Bi%5D.hasOwnProperty(sourceObject%5Bj%5D)%20%26%26%20(collection%5Bi%5D%5BsourceObject%5Bj%5D%5D%20%3D%3D%3D%20source%5BsourceObject%5Bj%5D%5D)%20)%20count%2B%2B%3B%20%0A%20%20%20%20%20if%20(count%20%3D%3D%3D%20sourceObject.length)%20arr.push(collection%5Bi%5D)%3B%0A%20%20%7D%0A%20%20return%20arr%3B%0A%7D%0A%0Awhere(%5B%7B%20first%3A%20%22Romeo%22%2C%20last%3A%20%22Montague%22%20%7D%2C%20%7B%20first%3A%20%22Mercutio%22%2C%20last%3A%20null%20%7D%2C%20%7B%20first%3A%20%22Tybalt%22%2C%20last%3A%20%22Capulet%22%20%7D%5D%2C%20%7B%20last%3A%20%22Capulet%22%20%7D)%3B%0A
// Learn to Code at Free Code Camp (www.freecodecamp.com)
function where(collection, source) {
var arr = [], count;
var sourceObject = Object.keys(source);
for ( var i = 0; i < collection.length ; i++) {
count = 0;
for ( var j = 0; j < sourceObject.length ; j++)
if (collection[i].hasOwnProperty(sourceObject[j]) && (collection[i][sourceObject[j]] === source[sourceObject[j]]) ) count++;
if (count === sourceObject.length) arr.push(collection[i]);
}
return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment