Wherefore art thou issues

Tell us what’s happening:
Hi,
My code is able to pass most of the test cases except for two of them. However for the first test case the result is quite strange as it returns a string that spells “[object Object],[object Object]”. Any help with this would be greatly appreaciated, thanks!

Your code so far


function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [...collection];
  // Only change code below this line
  for (let item in source){

    for(let i=0;i<collection.length;i++){
      if (collection[i][item]!== source[item]){
        collection.splice(i,1);
      }
    }
  }
  
  // Only change code above this line
  return collection;
}

let name=whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
for (let i=0;i<name.length;i++){
  for(let item in name[i]){
    console.log(name[i][item]);
  }
}

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0.

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

Hi,

collection.splice(i,1);
You are removing elements from this array collection while looping over it with an index so sometimes elements are totally skipped. If they’re skipped, they are never tested. If they are never tested, then they couldn’t be removed from collection. If you log element as below you will see that some are skipped

for(let i=0;i<collection.length;i++){
      console.log("testing", collection[i]); //output current test element
      if (collection[i][item]!== source[item]){
        collection.splice(i,1);
      }
    }

Probably better that you copy matches to arr rather than splice the non-matches out of collection.

You probably could make this work but logic seems more difficult to me

for (let item in source){ // for each prop in source

    for(let i=0;i<collection.length;i++){ // check each element in collection for match
      if (collection[i][item]!== source[item]){ //if not match,
        collection.splice(i,1);                 // then remove non-matching element
      }
    }
  }

This logic seems easier to implement

// for each element in collection
    // test if every prop in source matches prop in collection[i]
    // if yes, then push collection[i] onto arr

return arr

… avoids the looping over array while removing items thing and it leaves your passed array intact.