FreeCodeCamp Beta Wherefore art thou questions


#1

Hello, i need help for 2 things. First i don’t know why the “return true;” is here:

function whatIsInAName( collection, source ) {
	let keyNames = Object.keys(source);
	let keyL = keyNames.length;

	return collection.filter( function( obj ) {
		for( let k = 0; k < keyL; k++ ) {
			if( !obj.hasOwnProperty( keyNames[k] ) || obj[keyNames[k]] !== source[keyNames[k]] ) {
				return false;
			}
		}
		return true;
	});
};

And secondly, this code is what i did at the beginning but i failed:


function whatIsInAName( collection, source ) {
	var arr = [];
	var keyNames = Object.keys(source);
	var sourceL = keyNames.length;
	
	for( prop in collection ) {
		for( let k = 0; k < sourceL; k++ ){
			if( collection[prop].hasOwnProperty( keyNames[k] ) ) {
				if( collection[prop][keyNames[k]] == source[keyNames[k]] ) {
					arr.push( collection[prop] );
				}else {
					arr = [];
					k = sourceL;
				}
			}
		}
	}

	return arr;
};

If some one could help me on both cases. Thanks


#2

The first solution is checking for a condition where either the source property is not in the collection element’s object or the collection element’s object’s property value does not match the source for the same property/value. It returns false when either of these conditions are met. The return true outside the for loop is there because the filter function expects a true value if the element in the collection needs to be included in the final answer. If you go through all the properties in the source object and do not find a situation where you need to return false, that means all of the source’s properties/values where in the collection element’s object, so you must return true.


#3

For the 2nd solution (which does not work), I used your code and added some console.log statements in so you could see what the values are of the things you are comparing in the conditions of your if statements. It is best if you open the following link on repl.it site so you can see a wider console.