tags:

views:

69

answers:

2

Like I have an array Array('one', 'three', 'two');, and, say, I want to delete the item three, how would I do it?

+2  A: 
var a = ['one', 'three', 'two'];
a.splice(a.indexOf('three'), 1);
alert(a);

for browsers that don't support indexOf there's a workaround https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf#Compatibility

stereofrog
It's important to note that not all implementations have either `splice` or `indexOf` yet. Where they don't exist, one has to add them.
T.J. Crowder
Also, I'm pretty sure your args to `splice` are messed up. Should be the other way around: `a.splice(a.indexOf('three'), 1);` See https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Splice
T.J. Crowder
Fixed the arg order.
T.J. Crowder
thanks!........
stereofrog
A: 
function RemoveArrayValue(arr, val)
{
   var result = [], //empty array
   j = 0, i, len = arr.length;

   for(i = 0; i < len; ++i)
      if(arr[i] != val)
         result[j++] = val;

   return result;
}

BTW:

the indexOf method is not part of the Javascript Array object under IE (also not part of IE8), but of the String object. If you want the indexOf method to be part of the JS Array object you must declare this in your code:

if (!Array.prototype.indexOf)
{
    Array.prototype.indexOf = function(val)
    {
       for(var i = 0, len = this.length; i < len; ++i)
          if(this[i] === val)
             return i;

       return -1;
    }
}
Marco Demajo
`indexOf` is part of the `Array.prototype`, but it hasn't been implemented by all browsers (IE lacks of it) this method is part of the ECMAScript 3rd Ed. Standard, and you should check if a native `Array.prototype.indexOf` exists before overriding it, because native implementations are lightning fast...
CMS
Right! Thank u 4 the comment. I updated the code above as u suggested. :)
Marco Demajo