I'm currently working on a challenge that requires:
Create a function that scans through an array of objects (first parameter) and returns an array containing objects that match the property and value pairs specified in the second parameter. For an object to be included in the result, it must have all the property-value pairs present in the source object.
My attempt at solving this is as follows:
function whatIsInAName(collection, source) {
var arr = [];
var srcKeys = Object.keys(source);
arr = collection.filter(function(obj) {
for (var i = 0; i < srcKeys.length; i++) {
return obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] == source[srcKeys[i]];
}
});
return arr;
}
whatIsInAName([
{ first: "Romeo", last: "Montague" },
{ first: "Mercutio", last: null },
{ first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
However, my implementation returns an empty array. I suspect I may not fully understand how the filter method works.
One proposed solution is as follows:
function whatIsInAName(collection, source) {
var srcKeys = Object.keys(source);
return collection.filter(function (obj) {
for(var i = 0; i < srcKeys.length; i++) {
if (!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]) {
return false;
}
}
return true;
});
}
// test here
whatIsInAName([
{ first: "Romeo", last: "Montague" },
{ first: "Mercutio", last: null },
{ first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
I would appreciate a detailed explanation to help clarify why my approach doesn't yield the same output as the provided answer. Thank you for your assistance!
Your help is greatly appreciated.