function whatIsInAName(collection, source) {
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;
}
whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 })
the task: Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument).
What I understand:
we create an empty array for result
we loop through collection in order to get access to the objects
then we use for in loop to get access to key and value pairs
with an if statement we check if the values of collection are equal to the values of source
if they are not equal then the false flag drops to true
I do not get the full meaning of the code.
Can sb help pls? thanks
Hello:)
Why not just in a simple way in the first if statement they are looking for equality? If those things are equal then just push it in collectionMatches?
I tried it that way and it is not working.
here is that code:
function whatIsInAName(collection, source) {
let aaa = collection;
let bbb = source;
let res = [];
for(let i=0; i<aaa.length; i++){
for(let x in bbb){
if(aaa[i][x] === bbb[x]) {
res.push(aaa[i])
}
}
}
return res;
}
I can read that code, but I do not get the idea behind it. When you are reading a book but don`t get the message.
but the objects to keep from collection need to have all the property keys and values as source, your code finds one matching key and then puts the object in res, and if it finds a new matching key it puts the object in res again
you need to put an object in res only after checking that it has all the properties from source, not only one