var arr = new Array(1,2,3,4,5); arr.pop(); //delete 5
var arr = new Array(1,2,3,4,5); arr.shift(); //delete 1, arr now is [1,2,3,4]
var arr = [4,2,8,5,3,3,100,500]; var arr2 = arr.splice(3,1); //arr2 is [5] var arr3 = arr.splice(3,2); //arr3 is [5, 3]
If the 2nd paramenter is "0", followed by other parameters, then
var arr = [4,2,8,5,3,3,100,500]; var arr2 = arr.splice(3,0,11,12); //arr2 is [4,2,8,11,12,5,3,3,100,500]
To remove an element with its array position unknown, and based only on its value:
var arr = [4,2,8,5,3,3,100,500]; var indx = arr.indexOf(8); if (indx > -1) { arr.splice(indx,1); //arr is [4,2,5,3,3,100,500] } //if there are multiple positions with the same value var arr = [4,2,8,5,3,3,100,500]; var indx = arr.indexOf(3); while (indx > -1) { arr.splice(indx,1); indx = arr.indexOf(3); } //arr is [4,2,8,5,100,500]
If you want to delete an element and left the position empty istead:
var arr = [4,2,8,5,3,3,100,500]; delete arr[1]; //arr is [4,,8,5,3,3,100,500]
You may also define a remove method which can delete elements based on their value.
Array.prototype.remove = function (val) { var indx = arr.indexOf(val); while (indx > -1) { arr.splice(indx,1); indx = arr.indexOf(val); } } var arr = [4,2,8,5,3,3,100,500]; arr.remove(3); //arr is [4,2,8,5,100,500]