# Wherefore art thou functional solution

Hello fellow campers,

I am struggling a little with creating a functional solution for this algorithm, could someone indicate whether I am on the right track with this :

``````function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
// finds the keys that indicate data in the object
var sourceKey = Object.keys(source);
//takes the keys and returns the data associated
var sourceVal = sourceKey.map(function (key) {
return source[key];
});

var x = collection.forEach(function(int, idex){
var z = sourceKey.forEach(function(currVal, ind){
if (Object.values(int).includes(source[currVal])){
arr.push(int);
}

});
});
// Only change code above this line
return arr;

}

//whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1, "c": 5 }, { "a": 1, "b": 2, "c": 2 }, {"a": 1, "f": 0, "c": 2}], { "a": 1, "c": 2 });
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

``````

The above code passes the first two tests- I can see that it fails to test each object in the â€ścollectionâ€ť array for any more than one input from â€śinputâ€ť- I wonder if it is possible to complete the algorithm using a variation of this code.

Thanks

The reason it is not passing the other tests is because you are pushing int if a single property and value pair are found in an object in the collection. You only want to push if all the property value pairs are in it. The lines below are the issue:

``````     if (Object.values(int).includes(source[currVal])){
arr.push(int);
}
``````
2 Likes

Thank you for taking the time to look at my code- are you aware of a built in method which would allow me to check all property value pairs? Iâ€™m not looking for the answer, to be given to me, but Iâ€™ve not found anything like that in the docs.

Thanks again for taking the time

You might find `every()` useful. Also, if youâ€™re looking to do things in a more â€śfunctionalâ€ť manner, you might consider using the `filter` method instead of `forEach` + `if/else`.

3 Likes

OK- cool, thanks for a push in that direction!

Thanks to rmdawson71 and sa-mm for your assistance:

Here is my solution, I am learned a lot on this one:

``````function whatIsInAName(collection, source) {
// What's in a name?
var sourceKey = Object.keys(source);

var arr = collection.filter(function(int){
return sourceKey.every(function(currVal){
if (int.hasOwnProperty(currVal) && int[currVal] == source[currVal]){
return true;
}

return false;
});

});
return arr;
}
``````
1 Like

Very cool- I like that functional programming is easy to reason about once you grasp the input/ output of a given function