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.
splice() works both ways in addition and deletion. Let’s remove 3 from the above-mentioned array
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.
splice() method selects items from position 1 and then removes 2 items.
console.log(array); // Output: (3) [1, 4, 5]