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

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