Wherefore art thou algorithm challenge, solution only works for half the tests


#1

Below is my code

It works for the first two test cases but not the other two. I have no idea why since I’m pretty sure I did what was asked.

`
function whatIsInAName(collection, source) {
// What’s in a name?
var arr = [];
// Only change code below this line
var keys = Object.keys(source);

// loop through the whole collection
for (var i=0; i<collection.length; i++) {
// loop through the source array
for (var j=0; j<keys.length; j++) {
// if current object has the same property as the current source object
// AND their values are the same
if (collection[i].hasOwnProperty(keys[j]) && collection[i][keys[j]] == source[keys[j]]) {
// if it’s not already in the returned array, add it.
if (!arr.includes(collection[i]))
arr.push(collection[i]);
}
}
}

// Only change code above this line
return arr;
}

whatIsInAName([{ first: “Romeo”, last: “Montague” }, { first: “Mercutio”, last: null }, { first: “Tybalt”, last: “Capulet” }], { last: “Capulet” });
`

Thank you for your time.


#2

Sorry about the format, I forgot you need ``` not just `

function whatIsInAName(collection, source) {
 // What's in a name?
 var arr = [];
 // Only change code below this line
 var keys = Object.keys(source);
 
 for (var i=0; i<collection.length; i++) {
   for (var j=0; j<keys.length; j++) {
     if (collection[i].hasOwnProperty(keys[j]) && collection[i][keys[j]] == source[keys[j]]) {
       if (!arr.includes(collection[i]))
         arr.push(collection[i]);
     }
   }
 }
 
 // Only change code above this line
 return arr;
}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });


#3

Your code does not meet this requirement of https://www.freecodecamp.com/challenges/wherefore-art-thou

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.

Couple console.log should help you see the bug

Also better to edit your original post for code formatting


#4

I got it now, I thought if 1 key-value pair from the source matches a key-value pair in an object from the collection, then the object is included. I solved it using a simple flag. Thank you.

For future reference if anyone finds themselves in this situation (the wording is a little confusing) -

EVERY SINGLE key-value pair in the source must be in an object in order for it to go in the returned array.