Tuesday, November 24, 2009

The correct way to delete an element from an array in JavaScript

In JavaScript, there exists an operator called delete.  This operator is used to remove properties from objects, and since arrays in JavaScript are really objects, it can be used to remove elements:

var arr = ['a','b','c','d','e'];
delete arr[2];

//arr is now ['a', 'b', undefined, 'd', 'e']

As you can see from the above code, the element is removed but this leaves a hole in the array because the element was replaced with undefined.

Therefore, the correct way to remove an element an array from an element is by using the splice method.



Arrays in JavaScript have a method called splice.  To remove an element from array, we will use it is like such:

var arr = ['a','b','c','d','e'];
arr.splice(2, 1);

//arr is now ['a', 'b', 'd', 'e']

The first argument is an index (ordinal) in the array from where to start deleting and the second element is the number of elements to delete. Thus, with 2 and 1 as parameters, we are starting at index 2 and removing 1 element. (Additional parameters get inserted into the array).

One thing to note is that with splice, the property with the value 'd' has it's key changed from 4 to 3 and because every property after the deleted property will be removed and reinserted with a new key, this might take a while for large arrays.