Skip to content

JavaScript remove an element from array | 4 Ways with examples

  • by

You can remove elements from Array using a pop method to remove elements from the end, shift method removes from the beginning, or splice method to remove from the middle.

Ways to JavaScript remove an element from the array

  • pop() method – removes from the End of an Array
  • shift() method- removes from the beginning of an Array
  • splice() method- removes from a specific Array index
  • filter() method- allows you to programmatically remove elements from an Array

Let’s see the example

Unfortunately there is not a simple Array.remove method. Let’s see example of with above methods.

1. pop() method

The pop method removes the last element of the array, returns that element, and updates the length property.

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var ar = [1, 2, 3, 4, 5, 6];
    ar.pop(); // returns 6	

	console.log(ar);

    </script> 
      
    
</body> 
  
</html>

Output:

JavaScript remove element from array

2. shift() method

The shift method works much like the pop method except it removes the first element of a JavaScript array instead of the last.

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var ar = ['zero', 'one', 'two', 'three']
    ar.shift(); // returns "zero"

	alert(ar);

    </script> 
      
    
</body> 
  
</html>

Output:

removes the first element of a JavaScript array

3. splice() method

The splice method can be used to add or remove elements from an array.

JS remove two elements starting from position three (zero based index):

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    var removed = arr.splice(2,2);

	alert(arr);

    </script> 
      
    
</body> 
  
</html>

Output: 1,2,5,6,7,8,9,0

4. filter() method

filter method creates a new array. filter() does not mutate the array on which it is called, but returns a new array.

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    var filtered = array.filter(function(value, index, arr){ return value > 5;});

	alert(filtered);

    </script> 
      
    
</body> 
  
</html>

Output: 6,7,8,9

Do comment if you have any doubts or other way to do it.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *