Not able to understand the logic of every() in this problem

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

  return collection.filter(function(obj) {
    return srcKeys.every(function(key) {
      return obj.hasOwnProperty(key) && obj[key] === source[key];

// test here
    { first: "Romeo", last: "Montague" },
    { first: "Mercutio", last: null },
    { first: "Tybalt", last: "Capulet" }
  { last: "Capulet" }

here, srcKeys properties are NOT present in every property of collection but are present only in few. why is it then returning true and how is filter working here that it gives us the array? im not able to understand the logic here.
can somebody please help? i’m stuck on this problem for a WEEK now.

Using array methods like filter and every can give you a very slick, clean function - but they’re not required to solve this challenge. When I’m stuck on something, I usually try to a less elegant solution first. Have you tried solving this challenge using basic for loops?

filter returns an array with some elements removed. As an argument it takes a function that has a return value. That function is called with each element of the array as the argument and if it returns a falsy value, then the element is removed from the filtered array.
every is a method that returns true or false based on whether all elements of an array meet a specific condition. the srcKeys.every() is the function that is used in the filter method, so it is called for every element of collection and determines whether each element of collection is filtered out or not.


srcKeys is just an array of strings, each representing a property name on the source object. When we srcKeys.every() we are checking that for every property name found in the source object, does the currently-filtering object both have that property and a matching value?

The outer filter function is running through the array of objects and testing them one at a time. What is it testing for? The presence of every key/value pair in source.

1 Like

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