Wherefore Art Thou - check my thinking

Hello!

After a lot of failed attempts and reading of other forum posts I managed to solve this problem…I would like to check that I am understanding exactly how this program works. I have put comments in describing what I think is happening - am I correct? Have I missed anything?

Thanks!

if you want someone to look at your code, it is polite to not give a screenshot, but to give the link to a repl or codepen or something or just paste the code.

I mean, if someone wanted to copy and paste your code to check it is working in the right way, how would that be possible like this?

My apologies, I wasn’t aware… Here is a copy and paste of the above:

function whatIsInAName(collection, source) {
var sourceKey = Object.keys(source); // returns an array which can be compared with collection. Necessary because an object can’t be compared to an array.
return collection.filter(function(obj) { //this returns the filtered array. The collect is parsed as obj.
return sourceKey.every(function(key) { //this determines what is filtered out. array.every() test whether all elements pass a test. The sourceKey array is parsed to the function as key.
return obj.hasOwnProperty(key) && obj[key] == sourceKey; //this is the test provided to the every function and it checks whether obj (collection) has the property (sourceKey) AND that the elements are identical
})

})
}

whatIsInAName([{ first: “Romeo”, last: “Montague” }, { first: “Mercutio”, last: null }, { first: “Tybalt”, last: “Capulet” }], { last: “Capulet” });

You need to wrap your code in triple backticks (three before the code block and three after).

Also, when you need multi-line comments, use /* ... */ instead of //.

Hey @kitfoster, welcome to forum!

Regarding your comments:

  1. You turn source into array of keys as you will need to iterate through them and array is perfect type for that.
  2. .filter() method takes callback function that expects boolean output, true - keep object in the collection, false - toss it.
  3. .every() method returns boolean (just what filter needs) and checks whether all keys in sourceKey array “pass test”, just like you said.

Two notes:

  1. “…is parsed as…” part is a bit confusing, deleting it brings much more sense in my opinion.
  2. To be picky, you don’t need to check if object hasOwnProperty(key) - if it doesn’t obj[key] === source[key] will evaluate to false anyway.
1 Like

Thanks so much. That is very helpful and makes sense :slight_smile: