Javascript: Remove Items from Array
I required some javascript for removing an item (or series of items) from an array. Thankfully, I found out how to do it from this thread in Google Groups.
e.g. (paste into HTML document):<script language="javascript"> // this is the original array var theArray = [17,2,5,675]; // these are the items I wish to remove from the array var toRemove = [17,2]; // it can be done with one item only as well // var toRemove = 5; // adding it as a prototype object enables it to be used from any array Array.prototype.removeItems = function(itemsToRemove) { if (!/Array/.test(itemsToRemove.constructor)) { itemsToRemove = [ itemsToRemove ]; } var j; for (var i = 0; i < itemsToRemove.length; i++) { j = 0; while (j < this.length) { if (this[j] == itemsToRemove[i]) { this.splice(j, 1); } else { j++; } } } } theArray.removeItems(toRemove); alert(theArray); </script>
Thanks to Grant Wagner for this. It also can be applied to server-side ASP pages as well as client-side HTML (after setting JavaScript as the page language). However, there seems to be something wrong with an array of form elements (they are comma-space seperated i.e. "2, 5, 75, 120"), so it has to be split using var arItems = String(Request.Form("items")).split(", ")
NB. Array.splice is used, but is not supported by all browsers.
There is also a method of doing it without using splice (thanks to Dr John Stockton for this) in this thread. I have not implemented it yet - might use it as client side code.
var Delenda = [], j, n = 0, T, U // Undefined value for (j = 0 ; j < toRemove.length ; j++ ) Delenda[toRemove[j]] = true // or 0 ! for (j = 0 ; j < theArray.length ; j++ ) if ( Delenda[ T = theArray[j] ] === U ) theNewArray[n++] = TFinally, there is a method using Regular Expressions (thanks go to Greg for this):
<script type='text/javascript'> function removeVal(arr, valToRemove){ // Normalize to a string like !val!!val!!val! var s = '!' + arr.join('!!') + '!'; // Remove targeted values with delimiters s = s.replace(new RegExp('!' + valToRemove + '!', 'g'), ''); // Remove delimiter added to end in step 1 s = s.replace(/^!/, ''); // Remove delimiter added to start in step 1 s = s.replace(/!$/, ''); // Convert to array return s.split('!!'); } function test(){ var arr = [2,1,2,2,5,7,12,15,21,2]; // Check case with end vals var s = arr.toString(); arr = removeVal(arr, 2) alert(s + '\n' + arr.toString()); } </script> <button onclick='test()' />test()</button>
Comments