Forum Moderators: open
How can I remove an array value in javascript? Just like unset in PHP....
[webmasterworld.com ]
var colors = new Array('red','blue','green');
colors.splice('blue',1);
alert(colors);
I've a feeling I have to use the key not the value in splice. But how can I find out the key?
How can I remove an array value in javascript?
I've a feeling I have to use the key not the value
You don't necessarily need to know which key it is, if you convert the array to a string and add unique 'bookends' (temporarily for handling purposes) to each value, you can then do a replace with nothing '' on the string, and re-convert back to an array:
<script type="text/javascript">var someString = 'a string with the word blue in it will not be affected';
var colors = new Array('blue', 'red', 'blue', someString, 'green', 'blue');//value is the value to remove,
//flags --> such as 'g' or 'i' for global removal ('g') or case insensitive ('i'),
//or 'gi' for both global and case insensitive, etc..
Array.prototype.removeByValue = function (value,flags) {
//we'll use a (hopefully) unique enough 'cutter' (the cut variable)
//which is highly unlikely to occur in any of an arrays values,
//to seperate the array's values when we convert the array to a string
var cut = '@.:.@:@:@', rex = new RegExp(cut + value + "¦"+ value + cut,flags);
//convert to string, do replacement (replace value with nothing--> ''),
//convert back to array with the .split()
return this.join(cut).replace(rex,'').split(cut);
};//examples:
alert('colors array:\n' + colors);
var colors2 = colors.removeByValue('blue'); //no flags sent, only removes first occurrence of value
alert('colors2:\n'+ colors2);
var colors3 = colors.removeByValue('blue','gi'); //global, case insensitive removal
alert('colors3:\n'+ colors3);
alert('colors array has been left unchanged:\n'+ colors); //the original array is not changed,
//unless you do:
colors = colors.removeByValue('BLUE', 'gi');
alert('colors array has been altered:\n'+ colors);
alert('freddy won\'t be found, but no problem:\n'+ colors.removeByValue('freddy'));
colors = colors.removeByValue(someString);
alert('now with someString removed:\n'+ colors);</script>
Please note, you may need to manually replace the single regex 'or' conditional "¦" (<--- should be single pipe) in the definition of the rex variable, as this forum tends to wreck them and may cause syntax error if not replaced.
[internetdoc.info...]