Remove specific item from an array in JavaScript

In this tutorial, we will learn various methods to remove specific items from an array in JavaScript. Removing a specific element from an array can be done using multiple methods, including splice, pop, and shift.

Remove an element using the splice( ), pop( ), shift( ) methods

splice( ) method
  • Using this method we can remove one or multiple elements based on the index and the count of elements that we give as arguments
  • splice( index , count of elements that we need to remove starting from the index we provided)
  • example:
    let arrayOfNos=[1,9,3,7,6,5,4,2,13];
    
    // I want to remove 7 which is at index 3
    // As I want to remove only one element my count is 1 if we give the count as 0 no element will be removed as we are giving the number of elements that are to be removed as 0
    
    arrayOfNos.splice(3, 1);
    console.log(arrayOfNos)
    
    
    
    

    Output:

    [1,9,3,6,5,4,2,13]

    In the above example at the place of  “1,” we can give the count that we want to remove

  • for example now I want to remove 4 elements from the given index number, as the index number is 3, 4 elements will be removed from the array starting from the element at index 3
  • here, the output will be  [1,9,3,2,13]
  • If we are not going to give any count value to the splice method then we will be getting an output removing all the elements from that particular index number we provide as an argument
  • for example I just remove the count number from the above code then my output will be
  • [1,9,3]
  • pop( ) method

    Using this method we can remove the last element of an array, we need not provide any arguments to it

  • let arrayOfPop=[10,20,30,40,50,80];
    
    // pop() method removes the last element and the removed element can be stored in a variable
    
    let removedOne=arrayOfPop.pop();
    
    // It gives the element which is removed
    console.log(removedOne);
    
    // It gives the array after removing the element
    console.log(arrayOfPop);
  • Output: 80
    [10,20,30,40,50]
  • shift ( ) method

    Using this method we can remove the first element of an array

  • let shiftArray=[10,20,320,459,50,180];
    
     // shift() method removes the first element and the removed element can be stored in a variable 
    
    let removedArray=shiftArray.shift();
    
     // It gives the element which is removed 
    
    console.log(removedArray); 
    
    // It gives the array after removing the element 
    
    console.log(shiftArray);
  • Output:  10
    [20,320,459,50,180]

 

Leave a Comment

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

Scroll to Top