7

Given array [{GUID, other properties}, ...],

How can I remove a specific object from a javascript array by its GUID (or any object property)?

I'm trying to use splice(),

var index = game.data.collectedItems.indexOf(entityObj.GUID);
if (index > -1) {
    game.data.collectedItems.splice(index, 1);
}

This won't work because I can't directly identify the value in the array, as such:

var array = [2, 5, 9];
var index = array.indexOf(5);

Shown here: How do I remove a particular element from an array in JavaScript?

Community
  • 1
  • 1
Growler
  • 10,676
  • 21
  • 100
  • 224

2 Answers2

1

I would recommend using the Array.prototype.filter function, like this

game.data.collectedItems = game.data.collectedItems.filter(function(currentObj){
    return currentObj.GUID !== entityObj["GUID"];
});

This would iterate through the elements of game.data.collectedItems and filter out the items for which the function passed as a parameter, returns false. In your case, all the objects will return true except the object whose GUID matches entityObj["GUID"].

Note: Since filter creates a new Array, we need to replace the old array object with the new array object. That is why we are assigning the result of filter back to game.data.collectedItems.

thefourtheye
  • 206,604
  • 43
  • 412
  • 459
  • This is awesome. Thanks for the explanation of how it works too. It would be cool though to splice from an array using object properties at some point. – Growler Feb 08 '15 at 07:26
  • 1
    @Growler Actually, first you need to find the index of the item in the array (which, as you figured, is not straight forward in your case) and then you need to use `splice`. That is why I recommended `filter`. Simply ditch the old array and construct a new one without the elements you don't want :-) – thefourtheye Feb 08 '15 at 07:30
  • I'm changing my question to add just the entity objects to the array, and not {GUID, entity object}. After, I guess change your answer accordingly :) – Growler Feb 08 '15 at 07:37
0

This should work on all Browsers:

function withoutPropVal(ary, propVal){
  var a = [];
  for(var i=0,l=ary.length; i<l; i++){
    var o = ary[i], g = 1;
    for(var n in o){
      if(o[n] === propVal)g = 0;
    }
    if(g)a.push(o);
  }
  return a;
}
var newArray = withoutPropVal(yourArray, 'Object Property Value to Leave those Objects Out Here');
StackSlave
  • 10,198
  • 2
  • 15
  • 30