beginner solution:
function whatIsInAName(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function (obj) {
for(var i = 0; i < srcKeys.length; i++) {
if(!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]) {
return false;
}
}
return true;
});
}
The tricky part about this algorithm is that all of the properties in source have to be in each member of collection that you return. So, how does this code do that part? Also, how does the “return true” statement after the for loop not override the for loop’s output? In other words, I can’t tell the difference between the code above and code below:
function whatIsInAName2(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function (obj) {
for(var i = 0; i < srcKeys.length; i++) {
return !obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]] ? false : true
}
});
}
How the two intermediate solutions work is obvious to me, but this works is not obvious, and I clearly don’t understand something fundamental about js
edit: to be more clear about the differneces between the code:
whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })
outputs :
[ { a: 1, b: 2 }, { a: 1, b: 2, c: 2 } ]
whatIsInAName2([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })
outputs:
[ { a: 1, b: 2 }, { a: 1 }, { a: 1, b: 2, c: 2 } ]
further edit: I know what a ternary operator is, and even if you turn the ternary operator in my second example into an if/else statement, the function’s output is not correct. I know why the output is not correct. I don’t know why the first, official beginner’s solution to the algorithm question, is correct. The way that it meets this: “Each property and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.” requirement.
Also, I know that the return true statement is in different places. That’s the point.