Wherefore Art Thou Suggestions?

I started this challenge but I am stuck. For some reason I can’t wrap my mind around how to get this to check for multiple keys. My code is below. Thank you for any advice you can give!


function whatIsInAName(collection, source) {
// What’s in a name?
var arr = [];
// Only change code below this line
key = Object.keys(source);
for(i=0;i<collection.length;i++) {
if(collection[i][key] == source[key]) {
arr = arr.concat(collection[i]);
}
}
// Only change code above this line
return arr;
}

The logic for this challenge is:

Check every object for every key-val pair.

You need a loop to check every object and a loop to check every key val pair. Therefore you need two loops not just one.

An aside:

Anyone know why FCC is suggesting the obj.hasOwnProperty() function? Isn’t it completely unnecessary? Wouldn’t arr.filter() and arr.every() be much better suggestions?

For some reason I can’t wrap my mind around how to get this to check for multiple keys.

For that, you could possibly use the filter() method on your collection with a callback function that loops through the source object keys.

So now the filter() method will pass each object inside collection, and then, each object will be evaluated inside by the callback function on each source object keys. (As we are looping through the source object keys.)

Afterwards, you should create several statement conditions to evaluate each object based on what the challenge requires. So if you want to keep an object return true, false otherwise.

####Example how the filter method works:

collection.filter(function callback (obj){
   If ("Keep condtion") { // Might need several condtions!
      return true; 
   }

   else if ("Removal condtion") {
      return false;
   }
);

/*
  Now, filter will only return a new array with all elements 
  that pass the test implemented by the callback function.
*/

####Remember:
The filter() callback function should return true or false only.


Let me know if you got any more questions,
Goodluck!

While indeed the arr.filter() and arr.every() are good suggestions, the obj.hasOwnProperty() function can be useful. This is because there are several ways to solve this challenge and everyone have a different approach to problem-solving.

So whatever suggested is useful, but the suggestions you offered are definitely helpful. (Personally, I used both obj.hasOwnProperty() and filter() to solve this challenge.

function whatIsInAName(collection, source) {
// What’s in a name?
var arr = [];

// Only change code below this line
var i,j;
var temp=Object.keys(source);
for(j=0;j<temp.length;j++)
{
for(i=0;i<collection.length;i++){
if(collection[i].hasOwnProperty(temp[j])&&collection[i].valueOf(temp[j])===source.valueOf(temp[j]))
{
arr.push(collection[i]);
}
}
}
// Only change code above this line
return arr;
}

Hi! I used the same concept and I think this code should run but it always returns an empty array.