Wherefore art thou - comparing values of properties in different objects doesn't work

Hey,

I’m working on this for several hours (Wherefore art thou intermediate algorithm challenge) and still can’t get a pass on the first test (3 others are green).


The problem is with comparing the values of given properties in else if. It doesn’t work. The flag should be changed to false but it somehow isn’t. What’s wrong?

function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];

  for (var i = 0; i< collection.length; i++)
    {
      var flag = true;
      for (var prop in collection[i]) {
        for (var propS in source) {
           if (collection[i].hasOwnProperty(propS) === false)
           {
             flag = false;
           }
          else if (source.propS != collection[i].props )
            {
              flag = false;
            }
        }
        
      }
      if (flag === true)
        {
          arr.push(collection[i]);
        }
    }
  
  return arr;
}

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

Somebody advised me to use filter() method, but maybe there’s a way without it?

else if (source.propS != collection[i].props )
  {
      console.log(source.propS);
      console.log(collection[i].props);
      flag = false;
  }

Try that and see what you get.

nothing because it never gets inside. (there were typos, i fixed them below). When i did this:
else if (source.propS != collection[i].prop)
{

              flag = false;
            }
      console.log(source.propS);
      console.log(collection[i].prop);

I get undefined. but when i would for example return collection[0].last it returns the value it’s supposed to. why?

When you use dot notation, you’re trying to look up the property of propS on the objects, not what the variable propS represents. Since there is no source.propS, you’ll only get undefined. You need to use bracket notation, like this

source[propS]
1 Like

You steered me onto the right track and it worked, without using filter(), thanks. I will try to do it again using filter() though :slight_smile:.
I need to read again something about notations… it’s all messed up in my head