Tell us what’s happening:
Here is my code, can someone explain to me why the result is an empty array? I still don’t understand where I made a mistake.
Your code so far
function whatIsInAName(collection, source) {
var arr = [];
var convertArr = Object.keys(source);
for (let i = 0; i < collection.length; i++) {
for (let j = 0; j < convertArr.lengt; j++) {
if (collection[i].hasOwnProperty(convertArr[j]) === false || collection[i][convertArr[j]] !== source[convertArr[j]]) {
return false;
} else {
arr.push(collection[i]);
}
}
}
return arr
}
var result = whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
console.log(result)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/78.0.136 Chrome/72.0.3626.136 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou
Well to start, there is no property convertArr.lengt
– still working on the logic bit.
Edit: So I went through your code, and there are a few issues. First, the return
statement inside the if statement is breaking out of the function entirely. It doesn’t simply break the loop, it exits the function and returns false
, completely bypassing the return arr
at the end.
I might suggest you change up your logic a little. Here’s some pseudocode to get you thinking. This is solely your nested if statement, the way you’re setting up the array and the keys works fine:
for (iterate over the collection array){
// Note that this line *has* to be inside the loop, as we want to re-set it each pass.
create an addToArray variable, set to true.
for (iterate over they convertArr array of keys) {
if (the current key DOESN'T exist in the current collection member, OR if the value for that key doesn't match the source value) {
set the addToArray variable to false
} // end of the if statement
// We don't need an else here, as we aren't actually doing the adding here.
} // end of the loop over the keys
// Here's where any adding to arr happens
if (addToArray is true){
add the current member of collection to the arr array
}
} // end of the iterating over the collection loop
// at this point, we've tested each member, and added the relevant ones.
return arr
1 Like
What a silly mistake, thank you very much !!!
Easy one to make. Logic issues are a little more challenging, but I hope that pseudocode can help you see the logic.
1 Like
Your suggestion really helped me a lot, I passed this test and learned a lot, thank you very much !!!