Wherefore Art Thou is driving me crazy

Tell us what’s happening:
Hi guys :slight_smile:
I ve been stuck at this challenge for two days. I made progress today but i feel like i hit a wall.

I think the problem here is that my callback function returns an element as soon as one key value pair is equal, i gave up and checked the solution but it only helped me clean my code a bit (i could just copy the code but i dont think thats fair)
I dont know how to make it so my callback function only returns once every source property is found in the collection object. I could turn each object into an array of keys to use every() but then i wouldnt be able to compare their values. Please help me, thanks!
Your code so far


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

// First i use a for loop to access the source properties with a variable
for (const wtv in source) {
arr = collection.filter(element => 
      
      {
//Here i'm cutting off short objects. I guess i wont need this after fixing whatever is wrong
        if (Object.keys(source).length > Object.keys(element).length) {return}
//comparing key value pairs
        for (const prop in element) {
    if (element.hasOwnProperty(wtv) && element[prop] === source[wtv]) {
        return element;
    }
    }
    }
  )
}
console.log(arr)
// Only change code above this line
return arr;
}

whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3});

Your browser information:

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

Challenge: Wherefore art thou

Link to the challenge:

I suspect that you’re right that the problem is that you have a return inside the for loop. How could you move it outside of the loop to make sure that you only return a truthy value if all of the properties match?

2 Likes

Sorry for not answering earlier! This helped me a lot, i ended up using the every method on an array of source keys.

Congratulations on working through the problem! Happy coding. :slight_smile:

2 Likes