Last updated on October 11, 2022
In the current version of JavaScript, there are multiple ways to remove an item from an array in JavaScript. Let’s suppose we have an array containing 5 items. Either it can be numeric or strings.
let array = [1, 2, 3, 4, 5];
In this article, we will be using different functions to remove an item from the above array.
filter()
method accepts the call-back function in the first parameter. It has the ability to create a new array for all elements when they pass in the call-back function.
let removeItem = 4;
array = array.filter(element => element !== removeItem);
console.log(array); // [1, 2, 3, 5]
In this above script, variable removeItem has value 4 that is going to be removed from the array. Next, a call-back function is the first argument of the filter()
method, that checks each element if it is not equivalent to variable removeItem and pushes it into the new array. In case of failure, it simply ignores that element for pushing into the new array.
Javascript’s built-in method splice()
works both ways in addition and deletion. Let’s remove 3 from the above-mentioned array
array.splice(2, 1);
The splice()
method can be call by adding a dot after the variable. We have passed two arguments which are 2 and 1.
The first argument means the position of an item in the array. Here splice()
method would select 3 because the index starts with 0. The second argument means the total number of items that has be removed from the array.
So the above splice()
method would remove one item from the array which is 3. We can check the array’s output after calling the splice()
method as below
console.log(array);
// Output : (4) [1, 2, 4, 5]
In another example, we will be removing 2 and 3. Since number 2 is in the second position so index would be 1.
array.splice(1, 2);
Here, the splice()
method selects items from position 1 and then removes 2 items.
console.log(array);
// Output: (3) [1, 4, 5]
To remove an item from array, we can use JavaScript’s splice() and filter() method.