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.
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.
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 from index
val1, 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);
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);
We can use the filter method to remove elements that match the filter.
let fruits = ['π', 'π', 'π']; let filteredFruits = fruits.filter( item => item != 'π'); console.log(filteredFruits);
RELATED TAGS
CONTRIBUTOR
View all Courses