Delete doesn't remove element

Delete doesn't remove element
0

#1

I solved the Wherefore art thou challenge by deleting the collection (see bellow)
However I had to go to the extra step of filtering out null values (which I had to get from Stackoverflow). This isn’t very elegant and I am sure unecessary. Why does delete replace the objects in the array with Null? I haven’t found a simple way to remove elements from an object. Can someone give me some insights on what I am misunderstanding.

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

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

#2

First, there’s no splice in your code.

To avoid the consequence of delete, you can construct a new array with only the desired values and then assign it to arr in the end.


#3

@lynxlynxlynx thank you for the correction. I tried splice (as shown bellow), but when that didn’t work I tried delete. Was I using splice wrong? or is there no way to remove a specific element from an array without filtering out nulls or construction a new array.

function whatIsInAName(collection, source) {
  // What's in a name?
  
  // Only change code below this line
  for (var key in source) {
  var i;
  for (i = 0; i < collection.length; i++) {
    
           if(collection[i][key] === source[key]){
             continue;
           }
          else {
            var index = collection.indexOf(collection[i]);
            collection.splice(index,1);
          }
    }
   }
//   var arr = collection.filter(function(n){ return n != undefined }); 
  // Only change code above this line
  return collection;
}

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

#4

Splice should work fine. Make sure you’re using a good index there, the line looks suspicious (index==i).


#5

The delete operator is used to remove a property from an object, not an item from an array.


#6

Arrays are objects, so it works.


#7

I works-ish, but not the way that one would expect. The question was why delete left an empty placeholder in the array instead of removing it cleanly (as expected with an object literal).


#8

thanks @lynxlynxlynx and @ArielLeslie this conversation has helped me tremendously.