Remove string element from javascript array

can someone tell me how can i remove a string element from an array I have google and everything i get is deleted by index number

my example:

var myarray = ["xyz" , "abc" , "def"] ; var removeMe = "abc" ; myarray.remove(removeMe) ; consle.log(myarray) ; 

this is what i get from the console:

 Uncaught TypeError: Object xyz,abc,def has no method 'remove' 

jsfiddle

+7
source share
3 answers

From overflow.site/questions/14237 / ... :

 Array.prototype.remove= function(){ var what, a= arguments, L= a.length, ax; while(L && this.length){ what= a[--L]; while((ax= this.indexOf(what))!= -1){ this.splice(ax, 1); } } return this; } var ary = ['three', 'seven', 'eleven']; ary.remove('seven') 

or by making it a global function:

 function removeA(arr){ var what, a= arguments, L= a.length, ax; while(L> 1 && arr.length){ what= a[--L]; while((ax= arr.indexOf(what))!= -1){ arr.splice(ax, 1); } } return arr; } var ary= ['three','seven','eleven']; removeA(ary,'seven') 

You need to make the function yourself. You can either iterate over the array, or delete an element, or execute this function for you. In any case, this is not a standard JS feature.

+6
source

Since you are using jQuery

myarray.splice($.inArray("abc", myarray), 1);

EDIT If the item is not in the array, this "single line" is likely to cause an error. Something a little better

 var index = $.inArray("abc", myarray); if (index>=0) myarray.splice(index, 1); 
+16
source

Try for example

 myarray.splice(myarray.indexOf(removeMe),1); 

You can add this below script ( from MDN ) for browsers that do not support indexOf

 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { "use strict"; if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 0) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; } } 
+5
source

All Articles