Hi guys, working on this algorithm:
I need help understanding why a certain code doesn’t work.
So this is the solution I used to pass the challenge:
function whatIsInAName(collection, source) {
var srcKeys = Object.keys(source);
return collection.filter(function(element){
for (let i = 0; i < srcKeys.length; i++) {
if (!element.hasOwnProperty(srcKeys[i]) ||
element[srcKeys[i]] !== source[srcKeys[i]]) {
return false;
}
}
return true;
})
}
And then I tried changing the code to make it work using the opposite logic (using &&
instead of ||
and swapping true
and false
):
function whatIsInAName(collection, source) {
var srcKeys = Object.keys(source);
return collection .filter(function(element){
for (let i = 0; i < srcKeys.length; i++) {
if (element.hasOwnProperty(srcKeys[i]) && element[srcKeys[i]] == source[srcKeys[i]]) {
return true;
}
}
return false;
})
}
So in my mind, what should happen is that the filter method returns true when the element has the own property srcKeys[i] AND that property is equal to source[srcKeys[i]]. Giving me the same result as the previous code, but it doesn’t seem to do that.
Anyone can help me explaining why that happens?