Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to remove an element from an array in JavaScript

Programming Bytes

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 in-placethe operation is performed in the original array. For the 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);

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);

RELATED TAGS

javascript
communitycreator
RELATED COURSES

View all Courses

Keep Exploring