How can I remove a specific item from an array in JavaScript?

Javascript

Remove a Specific Value from an Array

To remove a specific value from an array using plain JavaScript:

function removeFromArray(array, value) {
    var index = array.indexOf(value);
    if (index !== -1) {
        array.splice(index, 1);
    }
}

If the value appears multiple times in the array, the above function will remove only the first occurrence. To remove all occurrences, use the following function:

function removeAllFromArray(array, value) {
    var index = array.indexOf(value);
    while (index !== -1) {
        array.splice(index, 1);
        index = array.indexOf(value);
    }
}

To use these functions, call them with the array and the value you want to remove:

var arr = [1, 2, 3, 4, 3, 5];
removeAllFromArray(arr, 3); // Remove all occurrences of value 3
console.log(arr); // Output: [1, 2, 4, 5]


Back to The Programmer Blog