Find matching name

Find matching name
0

#1

I’m trying to understand how the “Wherefore art thou” problem works. I can’t wrap my head around the whole code and how this works. I’ve read the hint and solution and I still don’t get it.

function whatIsInAName(collection, source) {
// What’s in a name?
var arr = [];
// Only change code below this line
var srcKeys = Object.keys(source);

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;
});

// Only change code above this line
}

whatIsInAName([{ first: “Romeo”, last: “Montague” }, { first: “Mercutio”, last: null }, { first: “Tybalt”, last: “Capulet” }], { last: “Capulet” });


#2

It gets all the keys from source and then filters the collection. To pass the filter, an item in collection has to contain all the keys. The solution breaks out of the filter and returns false if any of them fail.

In general, I think it’s better to come up with your own solution first than to try and understand the examples - there are definitely other ways to solve this and you’ll learn more by working through it in steps.


#3

ok so the reason why there is a for loop is because ‘collection’ has to have everything from ‘source’. And the if statement is saying "if there is no match from ‘source’ or the value of ‘source’ strictly does not equal whatever is in ‘source’ return false. Otherwise return true. Is that right?

I want to read and understand so that I could be able to think of my own codes for upcoming lessons.