How to remove item from array by value

  1 week ago     Views:  69  
Hardik Savani
1 Follows


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. Have a good day.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments