I am stuck with Shakespeare challenge

function whatIsInAName(collection, source) {
  var arr = [];
  var a = Object.keys(source);
  console.log(a);
  for (var i = 0; i < collection.length; i++) {
    for (var k = 0; k < a.length; k++) {
      if (collection[i].hasOwnProperty(a[k]) && collection[i][a[k]] === source[a[k]]) {
        arr.push(collection[i]);
      }
    }
  }
  return arr;
}

whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 });

What am I doing wrong? it’s weird.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

@IoanHadarean The previous moderator edited your post to include 3 backticks on the line before and after your code, to make it format correctly. Please do not remove these, so your code is more readable.

@IoanHadarean Before the inner for loop, you could create a Boolean variable which would act as a flag indicating whether or not the collection object should be added. You could start with this variable set to true and then your if statements would check for conditions of when you would not want to add the collection object. If such conditions are met, you would set this flag variable to false and break out of the inner for loop. After the inner for loop, you could check whether the flag variable is true. If it still is, then you can safely add the collection object to the final array. Otherwise, you would do nothing and let your outer loop continue to the next collection object.

@RandellDawson thanks for the help.