Skip to content

Instantly share code, notes, and snippets.

@cmcnealy
Last active June 26, 2020 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmcnealy/4116910667286eb1ec3ae0dab6d6d0cc to your computer and use it in GitHub Desktop.
Save cmcnealy/4116910667286eb1ec3ae0dab6d6d0cc to your computer and use it in GitHub Desktop.
freeCodeCamp | Intermediate Algorithm Scripting: Wherefore art thou: Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument). Each name and value pair of the source object has to be present in the object from the collection if it is to b…
function whatIsInAName(collection, source) {
var arr = [];
// Only change code below this line
arr = collection.filter(object => {
// function should return false for an object
// if one of the source keys does not exist
// or if an existing key's value does not match
let sourceKeys = Object.keys(source);
for (let i = 0; i < sourceKeys.length; i++) {
if (object.hasOwnProperty(sourceKeys[i])) {
if (object[sourceKeys[i]] != source[sourceKeys[i]]) {
return false;
}
} else {
return false;
}
}
return true;
});
console.log(arr);
// Only change code above this line
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
// should return [{ first: "Tybalt", last: "Capulet" }]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment