Wherefore Art Thou
Problem Explanation
Write an algorithm that will take an array for the first argument and return an array with all the objects that matches all the properties and values in the Object passed as second parameter.
Relevant Links
Hints
Hint 1
You may use for loop or the filter() method.
Hint 2
Consider using the hasOwnProperty() method to know if the property name exists in an object (as its own property).
Hint 3
Check if the value of the property in a collection objectmatches the values associated with the keys of thesource` object.
Solutions
Solution 1 (Click to Show/Hide)
function whatIsInAName(collection, source) {
// What's in a name?
const collectionMatches = [];
for (let i = 0; i < collection.length; i++) {
let foundMismatch = false;
for (const sourceProp in source) {
if (collection[i][sourceProp] !== source[sourceProp]) {
foundMismatch = true;
}
}
if (!foundMismatch) {
collectionMatches.push(collection[i]);
}
}
return collectionMatches;
}
Code Explanation
- We use a
forloop to iterate over every object in thecollection. - We check for a mismatching value between the
sources keys and the current object. - If no mismatch is found, the current object is added to the array of
collectionMatches.
Solution 2 (Click to Show/Hide)
function whatIsInAName(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
const souceKeys = Object.keys(source);
// filter the collection
return collection.filter(obj => {
for (let i = 0; i < sourceKeys.length; i++) {
if (obj[sourceKeys[i]] !== source[sourceKeys[i]]) {
return false;
}
}
return true;
});
}
Code Explanation
- We filter through the array using
.filter(). - Using a
forloop we iterate through each item in the object. - We use a
ifstatement to check if the value of the current property for the object matches the value in source. - We return
falseif any mismatch is found. Otherwise, we returntrue;
Solution 3 (Click to Show/Hide)
function whatIsInAName(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
const sourceKeys = Object.keys(source);
return collection
.filter(obj => sourceKeys
.every(key => obj[key] === source[key]));
}
Code Explanation
- We filter through the collection using
.filter(). - We return a
Booleanvalue for the.filter()method by checkif if.every()source key value matches the current object’s value.

)