solvit.io

Remove a specific element from a JavaScript array

Solution
function removeElement(array, element)
{
    var elementPosition = array.indexOf(element);

    if (-1 !== elementPosition) {
        array.splice(elementPosition, 1);
    }
}
Example
var array = [4, 8, 'foo', 15, 16, 'bar', 23, 42];
removeElement(array, 'bar');
// array = [4, 8, 'foo', 15, 16, 23, 42];

removeElement(array, 23);
// array = [4, 8, 'foo', 15, 16, 42];
Find more solutions about: ,