Wherefore art thou functional solution

Wherefore art thou functional solution
0

#1

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


#2

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

#3

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.


#4

Thanks again for taking the time


#5

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.


#6

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


#7

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

#8

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