Wherefore Art Thou - Stuck Passing 2/6

Tell us what’s happening:
I’ve been stuck on this particular challenge. I finally gave up and watched a video of someone working through it. I thought I understood what their code was doing so I recreated it line by line but it wouldn’t pass either. I then tried the attempt below. It passes the first two requirements but fails the last four. I tried putting it into a visualizer tool, but still can’t make heads nor tails of what’s going on.

Your code so far

function whatIsInAName(collection, source) {
var arr = [];
// Only change code below this line

let keys = Object.keys(source);

for (let i = 0; i < collection.length; i++) {
for (let j = 0; j <= keys.length; j++) {
    if (collection[i].hasOwnProperty(keys[j]) && collection[i][keys[j]] === source[keys[j]]){

// Only change code above this line
return arr;

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 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36.

Challenge: Wherefore art thou

Link to the challenge:

Hi there,
How do you filter through the collection? there should something wrong with the if condition.

1 Like

In this logic:

 if (collection[i].hasOwnProperty(keys[j]) && collection[i][keys[j]] === source[keys[j]]){

the answer array will receive any object from the collection which contains a matching object from the source object. The problem is if the source object has more than one key/value pair. In that case, both key/value pairs have to be tested in order for the match to be valid. The control statement needs to test for the absence of a match not just a match.

Hope this helps.

1 Like

Yes that does help. So my problem is that I’m not checking for both source keys and their values when the source has two or more keys.

I iterate through the collection using the first for loop with the “i” variable. I was trying to complete the challenge using just for loops since the set up says to only change code between those lines and return arr.

I eventually finished it using Arr.prototype.filter() and a for of loop