How to remove a specific element in array in JavaScript
remove = function(ary, elem) {
var i = ary.indexOf(elem);
if (i >= 0) ary.splice(i, 1);
return ary;
}
provided your target browser suppports array.indexOf
, otherwise use the fallback code on that page.
If you need to remove all equal elements, use filter
as Rocket suggested:
removeAll = function(ary, elem) {
return ary.filter(function(e) { return e != elem });
}
If you're using a modern browser, you can use .filter
.
Array.prototype.remove = function(x){
return this.filter(function(v){
return v !== x;
});
};
var a = ["a","b","c"];
var b = a.remove('a');
var newArray = [];
var a=["a","b","c"];
for(var i=0;i<a.length;i++)
if(a[i]!=="a")
newArray.push(a[i]);
As of newer versions of JavaScript:
var a = ["a","b","c"];
var newArray = a.filter(e => e !== "a");
I came up with a simple solution to omit the necessary element from the array:
<script>
function myFunction()
{
var fruits = ["One", "Two", "Three", "Four"];
<!-- To drop the element "Three"-->
<!-- splice(elementid, number_of_element_remove) -->
fruits.splice(2, 1);
var x = document.getElementById("demo");
x.innerHTML = fruits;
}
</script>