You would think that this would be part of JavaScript’s core functionality, but… no. It’s delete function leaves a value of “undefined” in place of the original. Using splice is the solution, but first you have to know the index of the element. These two simple functions make easy work of the task.
Object-oriented folk may want to enclose these functions within an extended array object (or extend the Array object, if that’s your style):
var getArrayIndex = function(array, item){ for (var i = 0; i < array.length; i++) { if (array[i] === item) { return i; } } return -1; }; var deleteArrayItem = function(array, item){ var index = getArrayIndex(array, item); if (index > -1) { return array.splice(index, 1); } return array; }
Using Array.indexOf might seem logical, but it’s mildly cross-browser problematic at the moment. Rather than using the common Array.indexOf workaround, I’m using a custom function because it’s less code and can be tweaked to suit any unique needs I might have.
Date: Wednesday, April 21st, 2010
Category: Web Dev