Aim is to build a function, which takes an array of Objects as first arguments. As a second argument it takes a key and value pair.
function whatIsInAName(collection, source)
Now the function should return an array with all the matching keys and values from the object. For example:
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })´
should return
[{ first: "Tybalt", last: "Capulet" }]
And
whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 })
should return
[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }]
I tried looping through the collection- and through the source array searching for matches. Like this:
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
for (var i = 0; i < Object.keys(collection).length; i++) {
for (var j = 0; j < Object.keys(source).length; j++) {
if (collection[i].last === source.last) {
arr.push(collection[i]);
}
}
}
console.log(arr);
}
And in case of this arguments whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })
It not surprisingly works.
What I don't understand is, why I can't generalize the above solution, so that it also works in other cases.
Why is it not possible to simply give the condition:
if (collection[i] === source)
(Pls notice the missing "Last"
key behind collection and source.)
When I console.log(source)
, console logs it. So imho the conditional statement above should work and should go to push the matches into the arr
Array.
How can I build a function which returns an array with all the matching keys and values from the object.
function whatIsInAName(collection, source)
And why does (collection[i] === source
) not work?
Thank you.