I have been trying to figure out this challenge for some time. Even looking at the basic solution, I can’t understand how the code works.
function whatIsInAName(collection, source) {
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;
});
}
// test here
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
I don’t understand how “return collection.filter(function (obj)” works. What is obj? The code doesn’t specify what “obj” is, yet somehow the input comes from somewhere.
I might have understood the problem just as I pressed the “publish” button.
Correct me if I’m wrong, but the filter function takes each element (collection[0]) in the array(collection), and compares the key to the one of the source.
So the reason collection.hasOwnProperty(“last”) doesn’t work is because “last” is not property of collection, but property of the first element in the array?
“obj” is just a name for the variable holding the current element of the array. It could be named anything, but “obj” seems fitting in this case since you are filtering an array of objects. You may want to look through filter() method page on MDN, it explains it well:
collection.hasOwnProperty("last") returns false because collection is an array, and arrays can only use integers for its elements’ indexes (0, 1, 2, 3 etc).
collection[1].hasOwnProperty("last") returns true because [1] refers to a specific element in the array, second element in this case, which corresponds to this object: { first: "Mercutio", last: null }. Now, objects DO store values in string indexes (they’re called keys, or properties), and this one does have “last” property, hence return of true.