Skip to content

Instantly share code, notes, and snippets.

@kseniya292
Last active July 24, 2016 15:02
Show Gist options
  • Save kseniya292/f1f8449f87c1f2b591184adacf7e5213 to your computer and use it in GitHub Desktop.
Save kseniya292/f1f8449f87c1f2b591184adacf7e5213 to your computer and use it in GitHub Desktop.
Where For Art Thou Algorithm- freeCodeCamp
function whatIsInAName(collection, source) {
var arr = [];
for (var i = 0; i < collection.length; i++) {
var collectionObject = collection[i];
//console.log(collectionObject);
//loop through collection array to look at the objects. Put the collection objects into a variable called collectionObject
var perfectMatch = true;
//set this variable to true. This will be changed to false when next loop fails.
for (var k in source) {
if (!collectionObject.hasOwnProperty(k)) {
perfectMatch = false;
} else {
if (source[k] !== collectionObject[k]) {
perfectMatch = false;
}
}
} //second for loop
//for every key in the source object, if a collection DOES NOT have the same key, set perfectMatch to false. Else, if it does match, check the value. If the value of the source key does not equal the value of the collection's object key, set perfectmatch to false. If any of the items match both in key and value, perfectMatch remains true.
if (perfectMatch) {
arr.push(collection[i]);
} // if perfectMatch is true, push that collection object into the array. Return that array below.
} //1st for loop
return arr;
} //function
whatIsInAName([{ 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