Question for "Intermediate Algorithm Scripting: Wherefore art thou"

Tell us what’s happening:

Hey guys. I want to ask about the filter method. In the solution, why is it that when the function returns true the console outputs:

[ { first: 'Tybalt', last: 'Capulet' } ]

I also don’t understand why return true; is outside of the for-loop and not after the if block.

I just cant wrap my head around it. Any explanation would be helpful.

Thank you!

Your code so far

function whatIsInAName(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
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 false;
  return true;

console.log(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/87.0.4280.141 Safari/537.36.

Challenge: Wherefore art thou

Link to the challenge:

Function passed to filter method is used to determine which elements from the array should be in the resulting array. Elements from the array are passed one-by-one to that function and if function returns true they are included in result.

return true; is outside of the for loop, because there can be multiple wanted properties, which all need to be present, with matching value, in element of array to be included in result. If property isn’t in the object false then is returned straightaway, but if it is present then function checks the next (if applicable) wanted property. And only if all those properties are present with correct values it can return true.

1 Like