How to remove an element from an array in JavaScript
Remove the first element of the array
The shift method in Array, will remove the first element of the array and return the removed element.
let fruits = ['π', 'π', 'π'];let removedFruit = fruits.shift();removedFruit; //'π'console.log(fruits);
We can use unshift method to add a new element to the beginning of the array.
Remove the last element of the array
The pop method in Array, will remove the last element of the array and return the removed element.
let fruits = ['π', 'π', 'π'];let removedFruit = fruits.pop();removedFruit;console.log(fruits);
We can use the push method to add a new element to the end of the array.
Remove array element by index
We can use the splice method to remove an array elements by index.
The splice() method modifies the contents of an array by removing or replacing existing elements and/or adding new elements splice method, we can send 3 arguments:
indexβ the index at which to start changing the array.deleteCountβ the number of elements in the array to be removed fromindexval1, val2, ...β the new values to be inserted at the index.
In our case, we only need to delete an element at the index, so we can set index and deleteCount as 1.
let index = 2;let fruits = ['π', 'π', 'π', 'π', 'π'];fruits.splice(index, 1);console.log(fruits);
Remove the array element by value
If you know the value of the item to be removed, we can use the findIndex method to find the element index and, using the splice method, we can remove the element from the source array.
let fruits = ['π', 'π', 'π', 'π'];let index = fruits.indexOf('π');if(index != -1) {fruits.splice(index, 1); // remove 1 element from index}console.log(fruits);
In the above code, we found the index of π and removed it. If youβre going to deal with object types, then use findIndex to find element index.
function callback(fruit) {if(fruit.item === 'π') {return true;}}let fruits = [ { item : 'π'}, { item: 'π'}, {item: 'π'}];let index = fruits.findIndex(callback);if(index != -1) {fruits.splice(index, 1); // from index remove 1 element}console.log(fruits);
Remove all the elements that match a value
We can use the filter method to remove elements that match the filter.
let fruits = ['π', 'π', 'π'];let filteredFruits = fruits.filter( item => item != 'π');console.log(filteredFruits);