Remove items from a JavaScript Array with RemoveArrayItems()
The RemoveArrayItems() function removes a set of numbers or strings from an array. The Javascript function takes two arrays as parameters, one being the array of items you want to manipulate and the other being a list of items you want to remove from the original array.
The function returns a new array with all the selected items removed.
A simple example of this function maybe you have an array containing a list of colors and you want to remove the red, green and blue entries. To do this you would simply pass in an array containing the colors to be removed.
function RemoveArrayItems(itemsToRemove,array) {
if(array.length==0||itemsToRemove.length==0) return array;
var sMatchedItems="|"+itemsToRemove.join('|')+"|";
var newArray=[];
for(var i=0;i<array.length;i++) {
if(sMatchedItems.indexOf("|"+array[i]+"|")<0) {
newArray[newArray.length]=array[i];
}
}
return newArray;
}
function RemoveArrayItems(itemsToRemove,array) {
if(array.length==0||itemsToRemove.length==0) return array;
//create a string containing all the items you want
//to remove from the array
var sMatchedItems="|"+itemsToRemove.join('|')+"|";
//new array with items removed
var newArray=[];
for(var i=0;i<array.length;i++) {
//loop through array and if any item in the array
//is not found in the matched items then add it
//to the new array
if(sMatchedItems.indexOf("|"+array[i]+"|")<0) {
newArray[newArray.length]=array[i];
}
}
return newArray;
}
<script type="text/javascript">
//create array with a selection of items
var array=new Array();
array[0]="apple";
array[1]="pear";
array[2]="orange";
array[3]="lime";
array[4]="lemon";
array[5]="grape";
//create an array with the items you want to
//remove from the original array
var itemsToRemove=new Array();
itemsToRemove[0]="orange";
itemsToRemove[1]="lemon";
//create a new array with the selected items removed
var newArray=RemoveArrayItems(itemsToRemove,array);
if(newArray!=null) {
//render the new list to browser
for(var i=0;i<newArray.length;i++) {
document.write(newArray[i]+"<br />");
}
}
</script>



