Wherefore art thou - code passing and I don't think it should

Wherefore art thou - code passing and I don't think it should
0

#1

Tell us what’s happening:

Your code so far

var propOfObject = [];
var valueOfObject = [];
var matchingArray = [];
propOfObject = Object.keys(source);
propOfObject.forEach(function(prop){
  valueOfObject.push(source[prop]);
});

for (var i = 0; i < collection.length; i++) {
  for (var j = 0; j < propOfObject.length; j++) {
    if (collection[i].hasOwnProperty(propOfObject[j]) && collection[i][propOfObject[j]] === source[propOfObject[j]] && j === valueOfObject.length-1){
        matchingArray.push(collection[i]);
      }
    }
}
return matchingArray;
}
whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 42, "b": 2 });

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36.

Link to the challenge:

Hi everyone,

So basically, my issue is that my code is passing :smiley: I submitted my coding (wrongly) assuming that it wouldn’t pass because at the moment my code pushes the object in the array only if the last pair of the 2nd argument is matching. I wanted to check if my code was working when there was only 1 pair.

In the example above, no object should be pushed according to the exercise, because in my 2nd argument, a equals 42 which is a pair nowhere to be found in the objects of the array.

Shouldn’t the tests be different and add objects in the array where the last pair of the 2nd argument matches but not all of the other pairs?


#2

Yes, you’re absolutely correct. The tests should be improved, and indeed they have been:

Using this loophole, we can even shorten your code a bit:

function whatIsInAName(collection, source) {
  var propOfObject = [];

  var matchingArray = [];
  propOfObject = Object.keys(source);

  for (var i = 0; i < collection.length; i++) {
      var j = propOfObject.length - 1;

      if (collection[i][propOfObject[j]] === source[propOfObject[j]]){
        matchingArray.push(collection[i]);
      }
  }
  return matchingArray;
}
whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 42, "b": 2 });