So i was reviewing the code i wrote for Intermediate Algorithm Scripting section. When i do this i tend to go to github repository of FCC and check what kind of answers they came up with. This one was very similar to the one i wrote, but there is one minor difference which changes the results a bit.
Now i should mention that English is not my first language, therefore there is room for misunderstanding, the same goes for JavaScript in general so i might be very wrong.
This is the function i wrote:
function myFunction(collection, source){
properties = Object.keys(source);
return collection.filter(function(item){
return properties.reduce(function(total,property){
//line below is in question
return item[property] === source[property] && item.hasOwnProperty(property) && total;
}, true);
});
}
Here is solution from freecodecamp github repository:
function whatIsInAName(collection, source) {
var srcKeys = Object.keys(source);
return collection.filter(function (obj) {
return srcKeys.reduce(function (res, key) {
//line below is in question
return obj.hasOwnProperty(key) && obj[key] === source[key];
}, false);
});
}
Summary
Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching property AND value pairs (second argument). 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.
Now both pass the test on FCC, but the results are different when you consider some other test cases which in my opinion better represent what the challenge was looking for.
extra test case 1:
collection:
[{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 10, "b": 2, "c": 2 }]
source:
{ "a":1, "c": 2 }
In this case FCC function considers third object of collection to be matching with source object. That is however not true since parameter âaâ has value 10, not 1. My function returns empty array as expected.
extra test case 2:
collection:
[{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }]
source:
{ "b":2, "a": 1 }
Here FCC function returns an array which consists of all collection objects. That is however wrong result since second object of collection doesnât have parameter âbâ.
Conclusion:
I may be really bad at understanding English, confused or tired, but it doesnât look right to me.
This line in FCC code does not take into consideration previous result, so it will return Boolean coming from logical operation performed only on last element of keys array, while simply ignoring previous ones. Also initial value is set to âfalseâ.
return obj.hasOwnProperty(key) && obj[key] === source[key];
My code takes into consideration results of previous logical operations. Init value is set to true.
return item[property] === source[property] && item.hasOwnProperty(property) && total;
Jsbin with mind boggling amounts of console.logs: