To remove elements or items from any position in an array, you can use the splice()
array method in JavaScript.
Consider this array of numbers,
// number array
const numArr = [23, 45, 67, 89];
What if we need to remove the element at index 1
in the array, in our case 45
.
We can do that with the splice()
array method. The method can be used to delete a group of elements from an array, starting from a particular index.
We can define the starting point to start deleting elements from the array by passing an index
number as the first argument to the method.
In our case let's remove 45
which is at index 1
.
// number array
const numArr = [23, 45, 67, 89];
// remove element 45
// at index 1
// But this is wrong ❌ for our case
numArr.splice(1);
console.log(numArr); // [23] 😕
But the problem with the above code is since we defined only the starting point it starts deleting elements from the array and we lost the last 2 elements 67, and 89
along with 45
.
This can be solved by passing another number as the second argument to the method which is the number of elements to be deleted from the starting position. 😃
In our case, we don't need to delete any other elements other than the number 45
at index 1
. So let's pass 1
as the second argument to the method to delete only 1 element from the staring position like this,
// number array
const numArr = [23, 45, 67, 89];
// remove element 45
// at index 1 and
// pass 1 as second argument
// to tell method to
// delete 1 element
// from the starting index
numArr.splice(1, 1);
console.log(numArr); // [23, 67, 89]
Yay! 🌟. We removed only one element from the array 😃.
See this example live in JSBin.
Also, if you need the deleted elements from the array the method returns an array of deleted elements from the array.
// number array
const numArr = [23, 45, 67, 89];
// remove element 45
// at index 1 and
// pass 1 as second argument
// to tell method to
// delete 1 element
// from the starting index
const deletedElements = numArr.splice(1, 1);
console.log(numArr); // [23, 67, 89]
console.log(deletedElements); // [45]