How can I remove an elements from an array?

It's a little more complicated to remove an element from a JavaScript array than in some languages.

Instead of a convenient array.remove() method; the JavaScript has a variety of ways you can delete and clear array values depending upon your needs.

  • pop() Used to remove elements from the end of an array.
  • shift() Used to remove elements from the start of an array.
  • splice() Used to remove elements from the specific index of an array.
  • filter() Used to create a new array with elements removed programmatically.

Remove a Single Item

Removing elements from end

The pop method removes the last element of an array and updates the length property. The pop() method modifies the existing array and returns the removed element.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9 ,10];
    
arr.pop(); // returns 10
    
console.log( arr ); // [1, 2, 3, 4, 5, 6 ,7 ,8 ,9]
Remove the element from the end

Removing elements from beginning

The shift method works much like the pop() method, except it removes the first element of a JavaScript array instead of the last one. The shift() method modifies the existing array and returns the removed element.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9 ,10];
    
arr.shift(); // returns 1
    
console.log( arr ); // arr = [2, 3, 4, 5, 6, 7, 8, 9 ,10]
Remove element from the start

Remove element from the middle

If you want to remove a single element from some point in the middle of an array, find the index of the array element you want to remove using indexOf(), and then remove that index with splice.

indexOf() returns the first index at which a given element is found or -1 if it is not present, you will need to check for this before removing with splice. Only the first instance will be removed if the same element exists at multiple indexes.

const arr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];

const index = arr.indexOf(5);
if (index > -1) { // only splice array when item is found
  arr.splice(index, 1); // 2nd parameter means remove one item only
}

console.log(arr); // arr = [1, 2, 3, 4, 1, 2, 3, 4, 5]
Remove the first element to match

Remove Multiple Items

Remove from the end

You can remove multiple elements from the end of an array by setting the length property to a value less than the current value. Any element whose index is greater than or equal to the new length will be removed.

 var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
 arr.length = 4; // set length to remove elements
 console.log( arr ); // arr = [1, 2, 3, 4]
Remove elements with an index freater than 4

Remove all matching element

If you want to remove all instances of a specific element from an array, there are two different options. Both methods achieve the same outcome but have different pros and cons depending on what you are doing:

  • splice() lets you remove an element from the original array.
  • filter() doesn't touch the original array and returns a new filtered array.
Regarding speed, splice() is the faster method; however, the difference is negligible on small arrays.

I prefer to use filter() as it's more readable, and I only use splice if working with a significantly large array with over 1,000 elements.

Remove all matching element with a splice() loop

The while() loop will iterate through each item in the array and check the value of each element for a match. If it finds a match, it will remove it using the splice() method.

let arr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];

let i = 0;

while (i < arr.length) {
   if (arr[i] === 5) {
      arr.splice(i, 1);
   } else {
      ++i;
   }
}

console.log(arr); // arr = [1, 2, 3, 4, 1, 2, 3, 4]
Remove all itmes that match with a loop
Using a forEach() loop can have unforeseen side effects as we mutate the array in the middle of the loop, causing the index to update. It's generally simpler to use a while() loop. See this JSFiddle https://jsfiddle.net/leviputna/94qsua5v/10/ for an example.

Remove all matching element with filter()

The filter() method creates a shallow copy of the array, iterates over the existing values and only returns the elements that pass (return true) the conditions of a test callback function.

Arrow functions can also be used to make JavaScript filter array code more readable.

let arr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];

const filterArr = arr.filter((el) => {
	return (el != 4);
});

console.log("Original Array", arr);
console.log("New Filtered Array", filterArr);
You've successfully subscribed to Twisted Brackets
Great! Next, complete checkout to get full access to all premium content.
Error! Could not sign up. invalid link.
Welcome back! You've successfully signed in.
Error! Could not sign in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.