Tell us what’s happening:
Help me please!! I was going through this code and I don’t understand how are these 3 return statement s working?
Your code so far
function whatIsInAName(collection, source) {
var srcKeys = Object.keys(source);
return collection.filter(function(obj) {
return srcKeys.every(function(key) {
return obj.hasOwnProperty(key) && obj[key] === source[key];
});
});
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
**Challenge:** Wherefore art thou
**Link to the challenge:**
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou
Hey welcome to forum I had a lot of trouble with this exercise and spent ages trying to figure it out. This is the best explanation I can write…hopefully others will chime in.
- The first return statement filters through the entire collection and returns true/false depending on certain criteria. We want the filter to return true for every element that matches srcKeys - this is where the second return statement comes in.
- .every() method returns a boolean (true/false ) which is what filter needs. This checks that all keys in srcKeys pass a test.
- The final return statement returns true when obj[key] == source[key]
Or to say it another way: the first return statement is necessary to filter through collection/obj. The second return statement is necessary to look through the values in srcKeys and returns true when a value is found that matches certain criteria. The third return statement is necessary to return true when obj[key] === source[key].
Is there anything specific that you are not understanding?