Wherefore art thou whats wrong i n this code

Wherefore art thou whats wrong i n this code
0

#1

Tell us what’s happening:

Your code so far


function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line
  for(let i=0; i < collection.length; i++){
   for(let n in collection[i]){
   if(n === source){
     arr.push(collection[i]);
   }
   }
   }
  
  
  // Only change code above this line
  return arr;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou


#2

n is a key of an object and source is an object. Therefore, n === source doesn’t make sense. Also, the actual comparison has to be done with values of objects.


#3

What is your question? You are not asking a question.


#4

I’m a little baffled: why are you doing a for/next loop AND a for/in loop? The whole for(let n in collection[i]) bit is causing you problems. Look at your passed parameters: collection is the array you are filtering, and source is the object you’re filtering BY.

So you could do the for/in loop, in fact you HAVE to, but you need to do something like for(let key in source){...} there instead. Using that, you iterate over all keys in the source object, and check each collection[i] against them.

Make sense?

**Note: ** So I reviewed the problem, and actually using a for/next and for/in won’t give you the result you want. They way you’re doing it, if you match ANY property, you add the object. And if you match a SECOND property, you add it again. And so on.

Instead, take a look at the Array.filter() method, which by this point in the curriculum, you should have an understanding. Array.filter() will allow you to iterate over the collection, and use the source object’s keys to see if they match. If any DON’T match, return false to the filter method, eliminating the current element from the returned array. Otherwise, returning true will include the current element.


#5

arr = Object.keys(source);

return collection
.filter( function (obj) { return arr
.map( function (key) { return obj
.hasOwnProperty(key) && obj[key] === arr[key]; })
.reduce( function (one, two) { return one && two; }); });


#6

What is this supposed to do?


#7

It use array of all keys to get a map of true and false statsments by checking conditions of key/value pair and existing of values in “collection” and “source”. Reduce this map to single logical statment wiht operator AND. And use this statment to return a filtered “collection”.
Sorry for possible inaccuracy, i do not have much practice in English.)