Remove an Element from an Array in Javascript

The simplest way to remove a particular element from an array in Javascript is to use the “splice()” method.

First find the index of the element you want to remove with the indexOf() method. 

var arr = ["apple", "mango", "orange", "banana"];
// say you want to remove "orange"
var i = arr.indexOf("orange");

Then remove the element with “splice()” method.

// 
if( i > -1 )
arr = arr.splice(i, 1);
// result ["apple", "mango", "banana"]

Note that the conditional check is required else if the index is not present then it takes the value -1 and the last element in array will be removed! Also, indexOf is not supported in IE 8 and below and older browsers. To get around that use the polyfill below:

Array.prototype.indexOf || (Array.prototype.indexOf = function(d, e) {
    var a;
    if (null == this) throw new TypeError('some error message here');
    var c = Object(this),
        b = c.length >>> 0;
    if (0 === b) return -1;
    a = +e || 0;
    Infinity === Math.abs(a) && (a = 0);
    if (a >= b) return -1;
    for (a = Math.max(0 <= a ? a : b - Math.abs(a), 0); a < b;) {
        if (a in c && c[a] === d) return a;
        a++
    }
    return -1
});