Skip to content

Remove first n elements from Array JavaScript | Example code

  • by

There are two methods in JavaScript Remove the first n elements from Array. If you want only the first element to remove then use the shift() method or if want n number of elements then you have to use the splice() method.

splice(start, deleteCount)
  • shift() method: Removes the first element from an array and returns that element.
  • splice() Method: Remove any item in an Array based on Index Value:

Remove first n elements from Array JavaScript Example

HTML example code.

Note: The splice() method changes the contents of an array by removing existing elements.

Remove the first 2 elements from Array.

<!DOCTYPE html>
<html>
<body>

  <script>
    var colors = ["red","blue","black","green"];
    var indexToRemove = 0;
    var numberToRemove = 2;

    colors.splice(indexToRemove, numberToRemove);

    console.log(colors);

  </script>

</body>
</html>

Output:

Remove first n elements from Array JavaScript

Do comment if you have any doubts or suggestions on this JS Array code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading