Wherfore Art Thou Challenge - Help!

I am having a lot of trouble with the Wherefore Art Thou Challenge. I had finally come up with this solution that works for the first 4 test values, but it doesn’t work for the last 3.

function whatIsInAName(collection, source) {
  let present = true;
  const newSource = [];
  const returnedArr = [];
  for (const checkName in source) {
    newSource.push([checkName,source[checkName]]);
  }
  for (let i = 0; i < collection.length;) {
    for (let j = 0; j < newSource.length; j++) {
      let title = newSource[j][0]
      if (collection[i].hasOwnProperty(title) && collection[i][title] === newSource[j][1]) {
        present = true;
      } else {
        present = false;
        i++;
        j = 0;
      }
    } if (present === true) {
      returnedArr.push(collection[i]);
    }
    i++;
  } 
  return returnedArr;   
}

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

When I try to test this code using those values, I get an error.

TypeError: collection[i] is undefined

When I debug this code in Visual Studio, it looks like the first for loop is being run with a value equal to collection.length. Why would it be doing this? Doesn’t it evaluate i < collection.length before it runs the loop again?

Could you explain what’s the reason for incrementing i both in inner and outer for loop?

1 Like

Thank you for pointing that out. I think I was just getting too frustrated with how long I was spending on this challenge. I have removed the i++s and have the for loop incrementing itself now. That got rid of the error and makes the code work for all but the 3rd and 5th tests. I’ll need to work on it some more. Thank you again, for pointing that out.

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