Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Created March 15, 2018 20:48
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 nickihastings/0f8b7f11d85600551da1d962798e0e79 to your computer and use it in GitHub Desktop.
Save nickihastings/0f8b7f11d85600551da1d962798e0e79 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. From FreeCodeCamp
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
var sKeyVal = [];
sKeyVal.push( Object.keys(source) ); //find the keys in the source
sKeyVal.push( Object.values(source) ); //find the values in source
var match = 0;
for(var i = 0; i < collection.length; i++){
cKeyVal = [];
cKeyVal.push( Object.keys(collection[i]) ); // find the keys in the first collection obj
cKeyVal.push( Object.values(collection[i]) ); //find the values in the first collection obj
if(sKeyVal[0].length > 1){
for(j = 0; j < sKeyVal[0].length; j++){ //test the coll keys against the source keys
index = cKeyVal[0].indexOf(sKeyVal[0][j]);
if(index != -1){
if(cKeyVal[1][index] == sKeyVal[1][j]){
match++;
if(match == sKeyVal[0].length){
arr.push(collection[i]);
match = 0;
}
} //end if cKeyVal
} //end if index
} //end for j
match = 0;
} //endif
else{
for(j = 0; j < sKeyVal[0].length; j++){ //test the coll keys against the source keys
index = cKeyVal[0].indexOf(sKeyVal[0][j]);
if(index != -1){
if(cKeyVal[1][index] == sKeyVal[1][j]){
arr.push(collection[i]);
} //end if cKeyVal
} //end if index
} //end for j
}//end else
} //end for i
// Only change code above this line
return arr;
}
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