Loop inside filter method

Tell us what’s happening:
So I keep having this type error ‘TypeError: Cannot read property ‘0’ of undefined’ and I can’t figure out why. I tried some console.log inside the for loop to see what was defined and what wasn’t but I just don’t understand what’s wrong ?! :fearful:

Help me please :confounded:

  **Your code so far**

function whatIsInAName(collection, source) {

// Only change code below this line
let srcKeys = Object.keys(source); // array of properties of source

let filteredArray = collection.filter(item => {
    
    for (let i=0; i<srcKeys.length; i++) {
      console.log(item.last) // Montague
      console.log(srcKeys[0]) // last
      console.log(item.srcKeys[0]) // cannot read property '0' of undefined!?!?!!
      if (item.hasOwnProperty(srcKeys[i]) && item.srcKeys[i] == source.srcKeys[i]) {
        return true;
      } else {
        return false;
      }
    }
});
return filteredArray;
// Only change code above this line

}

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

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36.

Challenge: Wherefore art thou

Link to the challenge:

This is the value of collection. So, the first item in `collection is:

item1 === collection[0] === { first: "Romeo", last: "Montague" }
console.log(item1.first) // "Romeo"
console.log(item1.last) // "Montague"

Now, what do you expect item1.srcKeys[0] to return?

The above assumes item1 looks something like this:

const item1 = { srcKeys: ["stuff"] };

This might help further: Confused about "" and [] when calling property - #4 by Sky020

Hope this helps

1 Like

Thank you for the explanation! I am no longer confused :relaxed:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.