Struggling with Wherefore Art Thou challenge

Struggling with Wherefore Art Thou challenge
0

#1

Hello Campers,

This is my first post on this forum I hope you’ll help me.
I got stuck and can’t go further :frowning:
The code is below.
Kuba

function whatIsInAName(collection, source) {
  var arr = collection.filter(function (source){
    for (var i = 0; i < collection.length; i++){
           if ( collection[i].hasOwnProperty(source) ){
          console.log(collection[i]);
          }
        }
      });
return arr;
};

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

#2

I think you might not be understanding how filter works. When you write:

var arr = collection.filter(function (source){

the collection array will iterate over each element in it. You specified an argument name of source in the anonymous callback function of filter, during each iteration of collection, source will be an object. There is no need to use the for loop as you are trying to do, because the filter takes care of that. Remember that the filter function will only capture elements (objects in this case) if a value of true is returned from the callback function. Currently, your callback function does not specify a return value, so undefined gets returned during each iteration. Filter is expecting a Boolean value, so undefined is treated as false, so nothing gets returned which is why arr is an empty array.

Maybe you should try to solve it without the filter function and try to use for loop(s). Once you understand how to solve it with for loops, then you can easily solve it with higher order functions such as filter.