Wherefore out thou algorithm

Wherefore out thou algorithm
0

#1

Hi everyone,

I’m trying to solve the wherefore out thou algorithm and I seem to be stuck. I have gotten to the point where my code works for the first two test runs, but it fails the last two, returning only a blank array.

I am trying to solve the problem using if statements, and here is what I have come up with so far.

function whatIsInAName(collection, source) {
        var arr = [];
        var keys = Object.keys(source);
        //console.log(keys);
        //console.log(Object.keys(collection));
        
        if (keys.length === 1) {
            for (var i = 0; i < collection.length; i++) {
                if (collection[i].hasOwnProperty(keys) === true) {
                    if (collection[i][keys] === source[keys]) {
                        arr.push(collection[i]);
                    }
                }
            }
        } 
        
        return arr;
    }

I think that the problem is related to the fact that the third and fourth test cases have more than one value for the source parameter, but I’m not exactly sure how to fix it. I know (think) I’ll need an else statement for those values but I’m just not sure what to do.

Any help would be appreciated.


#2

This might be possible with nested if clauses, but there’s a simpler solution. Imagine you had two functions, one that checks an object and returns true if it has all of the properties in keys, and another function that returns true if all of the properties in ‘source’ have the same values as the same properties in an object. Then, for each object, you could do

if (propertiesFunction(thisObject, keys) && valuesFunction(thisObject, source)) {
  //do stuff here
}

This is the idea I used when solving this myself.