How to remove item from array by value

  199 views   6 months ago Javascript

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]