For loop inside a filter

Tell us what’s happening:

I’m looking at the basic code solution, but don’t really understand why how the for loop inside the filter function works.

After it loops through all the items in srcKeys, it will return multiple True or False, but i thought the filter function can only take one True or False. Please explain what happens here. Thanks!

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;
  });
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou

The filter method will apply the callback function to each element in the array. If the callback function returns a value of true for an element, then the element is kept in the final returned array.

I personally don’t like the solution given (combining higher order functions with for loops). I would rewrite the for loop to use the every method by just returning the result of the every method on the srcKeys array (like below). I believe this makes the whole thing much more readable.

return srcKeys.every(function (key) {
  return obj.hasOwnProperty(key) && obj[key] == source[key];
});
1 Like

Does it mean for each element in collection, the filter function will run through the whole for loop? In that case, each element in collection will get multiple True and false since some
elements in srcKeys will meet the condition and some won’t. How does the filter decide whether to keep an element or not?

No. Because of the way the for loop is structure each object (element of the filter method) will only return a single true or false value. Why? Because the return statement inside the for loop and outside the for loop only return a single true or false value back to the filter method. Once a return statement is executed inside a function (the filter method callback function in this case), the for loop stops for that particular object (element) of the collection.