JavaScript - Intermediate Algorithm Scripting
I am trying to make a JavaScript function to look through an array of objects (first argument) and return an array of all objects that have matching property and value pairs.
Although the correct solution is given at freeCodeCamp, I would like to know what are the problems and errors in my code. Also, I found a solution on stack overflow, but I am not getting what's wrong with my code.
Here's my code
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
var obj;
var prop;
var keys = Object.keys(source);
for (var i = 0; i < collection.length; i++) {
for (var j = 0; j < Object.keys(source).length; j++) {
obj = collection[i];
prop = Object.keys(source)[j];
if (obj.hasOwnProperty(prop) && obj.prop === source.prop) {
arr = arr.concat([obj]);
}
}
}
// Only change code above this line
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
Here is the result I am getting
[{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]
Instead of
[{ first: "Tybalt", last: "Capulet" }]