Wherefore art though---Help requested

I’ve been working on this one for a few days now. I’ve seen an example of how to solve it, but I’m stubborn and I’d like to make my code work for all test cases, but I can’t solve it when the source argument has more than 1 key/value.

Would anyone mind giving me some feedback to help get my code working for all test cases?

Thanks for reading.

function whatIsInAName(collection, source) {

var output = ;

for (var object of collection) {
if (object[Object.keys(source)] === source[Object.keys(source)]) {
output.push(object);
}
}

return output;
}

I did this

var sourceKeys = Object.keys(source);

  return collection.filter(function(item){return sourceKeys.every(function(key){return item[key] === source[key];});});
}

Instead of using every you can nest for loops to search for every key.

Thanks for the code.

Here’s what I ended up going with:

> function whatIsInAName(collection, source) {
>   
>   var sourceKeys = Object.keys(source);
> 	var result;

>   return collection.filter(function(object) {
>     for (let i = 0; i < sourceKeys.length; i++) {
>       if (object[sourceKeys[i]] == source[sourceKeys[i]]) {
>         result = true;
>       } else {
>         result = false;
>       }
>     }
>     return result;
>   });

> }

I cleaned the solution @fuqted preseted for ES6:

var find = Object.keys(source);

 const matches = collection.filter(item => {
    return find.every( key => {
        return item[key] === source[key];
      });
    });

  
 arr.push(...matches);

Place // jshint esversion:6 into the first line of the editor if you want the es6 alerts to disappear.

That might’ve passed but try inputting ([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }) , then try changing the first object to {"a": "wrong" , "b":2} and it’ll still work, as long as the last one passes. As a rule, it’s always at least pointless when you use an if else statement to return either true or false. In this case you should define result as true before the loop and then if (object[sourceKeys[i] !== source[sourceKeys[i]]){ result = false; break; }

@joshpitzalis
Cool. I’ve been meaning to learn arrow functions. I think I get how they work now.

Can you explain what the “of” statement is doing in for (var object of collection) { . ? I’m assuming it functions to iterate through every index in the “collection” array, but I couldn’t find anything about an “of” statement online