[Solved | Spoiler] Wherefore Art Thou help needed

[Solved | Spoiler] Wherefore Art Thou help needed
0.0 0

#1

I know this probably isn’t the most ideal way to do it, but the code passes the first two challenges when the source object we are testing for has only one item in it, but when the challenges have two items in the source object it fails.

function whatIsInAName(collection, source) {

  // What's in a name?
  var arr = [];
  // Only change code below this line
  var sourceKeys = Object.keys(source);
  //user counter to compare sourceKeys w collection.
  var sameness = 0;
  for (var k = 0;k<collection.length;k++) {
    for(var l = 0; l<sourceKeys.length; l++) {
      if(collection[k][sourceKeys[l]] === source[[sourceKeys][l]])
        sameness += 1;
    }
    if(sameness === sourceKeys.length) {
      arr.push(collection[k]);
      sameness = 0;
    }
  }
  // Only change code above this line
  return arr;
}

Basically I’m going through on comparing the individual objects in collectoion with the source object and keeping track of their “sameness” in a variable. if sameness is the same as the sourceKeys.length, then it contains all the key value pairs in the source object and should be pushed to the arr array. Make sense?

Can anyone help me figure out what source objects with more than one key value pair are not passing?

Thanks!


#2

[UPDATE]
I figured out what was wrong with my code if anyone is interested.

AND I LEARNED A VALUABLE LESSON IN THE PROCESS! I placed my sameness = 0; inside the sameness === source.length! This means if the sameness counter didn’t match the length, it would continue with the first for loop but not reset the sameness var.

Always double check where you’re placing stuff! the code below works now

function whatIsInAName(collection, source) {
  //debugger;
  // What's in a name?
  var arr = [];
  // Only change code below this line
  var sourceKeys = Object.keys(source);
  //user counter to compare sourceKeys w collection.
  var sameness = 0;
  for (var k = 0;k<collection.length;k++) {
    for(var l = 0; l<sourceKeys.length; l++) {
      if(collection[k][sourceKeys[l]] === source[sourceKeys[l]]) {
        sameness++;
      }
    }
    if(sameness === sourceKeys.length) {
      arr.push(collection[k]);
      
    }
    sameness = 0;
  }
  // Only change code above this line
  return arr;
}