Wherefore art thou challenge help

Wherefore art thou challenge help
0.0 0

#1

Hi guys. I’m really confused by the behaviour of my code, mainly the last bit. I’ve got close but not sure why at the end the object { a: 1, b: 2, c: 2 } gets spliced out and not { a: 1 }. Can anyone help? Thanks in advance

function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  var arr2 = [];
  var place = "";
  var hai = "";

  // Only change code below this line
  
    for (var prop in source) {
      if (source.hasOwnProperty(prop)) {
        place = prop;
        hai = source[place];
        console.log(hai);
        console.log(place);
      
        for (i=0; i<collection.length; i++) {
          if (collection[i][place] == hai && arr.indexOf(collection[i]) < 0) {
            arr.push(collection[i]);
            console.log(arr);
          }
        }
      }
    }



  for (var j=0; j<collection.length; j++) {
    if (!collection[j].hasOwnProperty([place])) {
      arr.splice(j, 1);
      console.log(arr);
    }
  }
  
  
  // Only change code above this line
  return arr;
}

whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "c": 2 })

#2

I think it’s because .splice() changes the array. After you splice first time, the indexes of arr and collection don’t align anymore.

EDIT:
Also your usage of prop in second loop is strange.

I didn’t dig deep into your code, it’s just an observation.


#3

That was it, managed to figure it out and solve it, thanks!

My code may be strange, I don’t think my solution was very elegant but it got the job done so good enough I guess