Wherefore art thou - Using for...in loop and for loops - HELP!

Tell us what’s happening:

Hello, I’ve been trying to solve this problem since yesterday and it seems like I’m doing most of the stuff right. However, the array length is giving me some trouble. Can you guys review my code and see what’s the issue? If possible, please correct the code and comment out the problematic lines.

Your code so far


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

console.log(whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou/

The problem is here:

if (collection[j][sourcekeys[i]] === source[property]) {
     arr.push(collection[j]);
}

You’re pushing the entire collection when only 1 source matches.
You should only be pushing when all sources are present in a collection.

I think they want the full array of objects like stated below:

“returns an array of all objects that have matching name and value pairs (second argument).”

Edit: I managed to solve all the required parts except one yesterday though, but then ended up going to the hints section and reading the full code.