Help with understanding Wherefore art thou

Hi guys, working on this algorithm:

I need help understanding why a certain code doesn’t work.

So this is the solution I used to pass the challenge:

function whatIsInAName(collection, source) {

  var srcKeys = Object.keys(source);

  return collection.filter(function(element){

          for (let i = 0; i < srcKeys.length; i++) {

            if (!element.hasOwnProperty(srcKeys[i]) || 
                  element[srcKeys[i]] !== source[srcKeys[i]]) {
              return false;
            } 
          }
            return true;
        })
}

And then I tried changing the code to make it work using the opposite logic (using && instead of || and swapping true and false):

function whatIsInAName(collection, source) {

  var srcKeys = Object.keys(source);

  return collection .filter(function(element){

          for (let i = 0; i < srcKeys.length; i++) {

            if (element.hasOwnProperty(srcKeys[i]) && element[srcKeys[i]] == source[srcKeys[i]]) {

              return true;
            } 
          }
            return false;
        })
}

So in my mind, what should happen is that the filter method returns true when the element has the own property srcKeys[i] AND that property is equal to source[srcKeys[i]]. Giving me the same result as the previous code, but it doesn’t seem to do that.

Anyone can help me explaining why that happens?

It all depends on the early return and the condition satisfied.

The first one read as:

NOT ADD element 
  IF element IS NOT in collection 
  OR if element value  IS NOT EQUAL

The second reads as

ADD element 
  IF element IS in collection 
  AND element value IS EQUAL

Which means that in a case like this:

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

your first condition removes the element as “apple” is not present

while your second condition keeps it as “bat” satisfy both condition, but doesn’t satisfy the requirements.

[edit] should clarify that this is mainly due to the early return.
In the first case you remove the element as soon as something is wrong.
In the second case you add them as soon as the condition is met, but keep scanning for the condition even if you know that one previous element was false, which should have blocked the execution earlier.
Hope this helps :slight_smile:

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