Search

How to remove item from array by value

post-title

In your way to work in Javascript, you will might be needed to add or remove item from javascript array. You can simply add item into array with push() method.

In javascript, you can not directly remove item from array.xaFirst you need to find item index with indexOf() method in the array and need to remove that item. Here is the example.

var arr = [1, 3, 5, 7, 11];
var item = 7; 

function removeItem(array, item) {
    if (array.indexOf(item) !== -1) {
        array.splice(array.indexOf(item), 1);
    }
    return array;
}

console.log(removeItem(arr, item)); // [1, 3, 5, 11]

There is filter() method which can do same job as above function.

var arr = [1, 3, 5, 7, 11];
var item = 7; 
var newArray = arr.filter(function(e) { return e !== item });
console.log(newArray);

There are also other ways you can do with custom functions.

I hope it will help you.