Skip to content
Related Articles

Related Articles

Improve Article
How to remove specific elements from the left of a given array of elements using JavaScript ?
  • Last Updated : 30 Apr, 2021

In this article, we will learn How to remove specific elements from the left of a given array of elements using JavaScript. We have given an array of elements, and we have to remove specific elements from the left of a given array.

Approach: The splice() method is used to add and remove elements from an array. To remove specific elements from the left of a given array, we will use the splice method. To remove specific elements it takes two parameters index form where we want to remove the element and the number of the elements we want to remove. It returns an array that contains removed elements. 

Syntax:

array.splice(index,No_of_element);

Example:

HTML




<!DOCTYPE html>
<html>
  <body>
    <div>
      <p id="p" style="font-size: 18px">
        When we click on button the element 
        3rd elements will be removed from
        the array.
      </p>
  
      <p id="gfg">[2,4,5,3,6]</p>
  
      <button onclick="fun(5)">click</button>
    </div>
  
    <script>
      function fun(n) {
        // Array
        var arr = [2, 4, 5, 3, 6];
          
        // Find index of specified element which is n
        var ind = arr.indexOf(n);
          
        // And remove n from array
        arr.splice(ind, 1);
        document.getElementById("p").innerHTML = 
        "After remove element";
          
        // Final result after remove n from array
        document.getElementById("gfg").innerHTML = 
        "[" + arr + "]";
      }
    </script>
  </body>
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :