Filtering an Array of Objects

Tell us what’s happening:
Hello,

This challenge was particularly… challenging for me. I generally don’t look at the answers unless I am completely out of options, but this time I broke down after about an hour working on it and half a day mulling it over.

I understand the basic logic I think.

But why doesn’t this work?

  let key = Object.keys(source)

  return collection.filter(Obj => {
  			for (let i = 0; i < key.length; i++){
        	if (Obj.hasOwnProperty(key[i]) && Obj[key[i]] == source[key[i]]){
            return true;
          }
        }
  })

It seems like this is a rather simple type of problem, but I really was stumped. I’m not discouraged but I am worried my understanding is severly lacking.

Thank you for your time! Below is the solution that was accepted (I had to look it up).

  **Your code so far**


function whatIsInAName(collection, source) {
// Only change code below this line
const key = Object.keys(source)


return collection.filter(Obj => {
			for (let i = 0; i < key.length; i++){
      	if (!Obj.hasOwnProperty(key[i]) || Obj[key[i]] !== source[key[i]]){
          return false;
        }
        
      }
      return true;
})

}


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

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

Challenge: Wherefore art thou

Link to the challenge:

The problem is this part of the if statement inside the for loop. If it finds the key in both source and Obj, the statement evaluates to true. The problem is it only takes matching one of the keys in source. All properties (keys) in source must be present in Obj to get included in the final array, not just one.

That is why in the following test case:

whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }))

your function returns one extra object ({ "bat": 2 }) because bat is in source and Obj, but apple is not part of the { "bat": 2 } object, so it should not be included.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.