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?