JS Remove Array Elements


pop() method: delete 1 element from the array end, return the element:

var arr = new Array(1,2,3,4,5);
arr.pop(); //delete 5


shift() method: delete 1 element from the array start, return the element:

var arr = new Array(1,2,3,4,5);
arr.shift(); //delete 1, arr now is [1,2,3,4]


splice(i,n) method removes elements of an array, and return the new array contains the removed elements. "i" - array position, "n" - how many elements to be removed.

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 splice(i,0,...) method adds elements to the array.

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]




endmemo.com © 2024  | Terms of Use | Privacy | Home