I dont understand the differences between these 2 codes and why the 1st code produced the true answer and didnt meet the same problems as the 2nd code.
Please help me:
1st one:
function whatIsInAName(collection, source) {
const art = [];
for (let i = 0; i < collection.length; i++) {
let check = true;
for (const prop in source) {
if (collection[i][prop] !== source[prop]) {
check = false;
}
}
if (check) art.push(collection[i]);
}
return art;
}
console.log(whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1}, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }));
2nd code:
function whatIsInAName(collection, source) {
const art = [];
for (let i = 0; i < collection.length; i++) {
for (const prop in source) {
if (collection[i][prop] !== source[prop]) {
} else {
art.push(collection[i]);
}
}
}
return art;
}
console.log(whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1}, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }));
Challenge: Intermediate Algorithm Scripting - Wherefore art thou
The second argument can be an object with more than one property/value. If that’s the case then all of the property/values in the second argument must match before the item can be included in the returned array. Does that help you see why the second function won’t work?
I think i understand now. The point is the position of push(collection[i]);
The 2nd code push(collection[i]) everytimes there’s a property that makes collection[i][prop] == source[prop] so it’s obviously wrong.
Meanwhile the 1st code looks through the whole collection[i] and only return check = true when every property in 2nd argument matches. Only when meeting that condition, the code push(collection[i]) later.
I find it out when trying to understand what you said. Thank you so much.
Okay i’ve got confused now. I made a little change in the order of true/false as well as the condition, and it’s not work
function whatIsInAName(collection, source) {
const art = ;
for (let i = 0; i < collection.length; i++) {
let check = false;
for (const prop in source) {
if (collection[i][prop] == source[prop]) {
check = true;
}
}
if (check) art.push(collection[i]);
}
return art;
}