"Wherefore art thou" : filter

Hello,
Wherefore art thou

About the FCC solution 1:
Why it doesn’t work with positive filter ?

function whatIsInAName(collection, source) {
  var srcKeys = Object.keys(source);

  // filter the collection
  return collection.filter(function(obj) {
    for (var i = 0; i < srcKeys.length; i++) {
      if (
        obj.hasOwnProperty(srcKeys[i]) &&
        obj[srcKeys[i]] == source[srcKeys[i]]
      ) {
        return true;
      }
    }
    return false;
  });
}

If you are checking all elements of an array for a condition, are you able to say that all of them meet it after only after meeting the first one that matches the condition?

sorry I don’t undersatnd, furthermore it seems that google translate don’t make a good job with this sentence. :upside_down_face:

Yes I understand, if the first [i] return false not need to check [i++].
Correct ?

Because you ‘return true’ here even if only one of the srcKeys is inside.
Instead, you should only be returning true if every element in srcKeys is inside obj

Specific Example:

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

This test fails with your code because it returns every object including: { "bat": 2 }.
But, it should not return { "bat": 2 } , because you are testing for { "apple": 1, "bat": 2 }.

In other words, an object should only be returned if it includes apple and bat.
But your code is checking for apple or bat.

2 Likes

yes, I understood, thanks