DEV Community

Discussion on: Solving "Wherefore art thou" / freeCodeCamp Algorithm Challenges

Collapse
 
soumya98dev profile image
Soumyadeep Chatterjee

Great solution, but I did'not understood, why is the "return true" outside of the for loop. Then after each iteration where are the results of it is stored when the if is true.

Collapse
 
kartikongit profile image
kartikongit • Edited

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;
});
}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

collection is an array of objects
source is just a single object .. it can contain more than 1 keys

now we stored keys of the source object inside the sourceKeys array

sourceKeys is an array that stores the keys from source

we are returning a filtered array

we are filtering the collection array

we are only using 1 parameter of the callback function for the filter method

this function will be called for each object that resides in collection array

we have the hold of keys from source object

we have the hold of a single object from collection array

now we are going to perform a for loop ..

why for loop ?

what are we looping ?

we are looping through keys ...

and we get hold of the single key from the source key

lets say that key is "last"

now with an if statement we are checking the values of obj[last] !== source[last]

so here comes your question why is return true out of forLoop

well the for LOop is designed to only return false no matter what ... so even if all the key's values matches the for loop will only care about false values

and its job is to see if there is something that is not matching

but since we are using a filter method that actually just takes true values and rejects false values to be incluced

in the end if nothing matches nothing will be added to array

but if it matches the whole object is said to be true and that object will be included