Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MinSomai/f7c83581fd00a13495f4900bfb79bd2a to your computer and use it in GitHub Desktop.
Save MinSomai/f7c83581fd00a13495f4900bfb79bd2a to your computer and use it in GitHub Desktop.
Intermediate Algorithm Scripting: Wherefore art thou
function whatIsInAName(collection, source) {
var arr = [];
let matchingIndex = [];
collection.forEach((obj, index)=>{
let matchBool = matchesSource(obj, source);
if(matchBool)
matchingIndex.push(index);
});
matchingIndex.forEach(item=>{
arr.push(collection[item]);
});
return arr;
}
function matchesSource(obj, source){
let sourceKeys = Object.keys(source);
let matchCount = 0;
let matchesBool = false;
sourceKeys.forEach(key=>{
if(obj[key] == source[key]){
matchesBool = true;
matchCount++;
}
});
if(matchCount!=sourceKeys.length)
matchesBool=false;
return matchesBool;
}
whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 });
// QUESTION:
// 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 be included in the returned array.
// For example, if the first argument is [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], and the second argument is { last: "Capulet" }, then you must return the third object from the array (the first argument), because it contains the name and its value, that was passed on as the second argument.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment