How to Remove First and Last Element from an Array in Javascript?

Sep 14, 2022 . Admin



Hello dev,

This article will provide some of the most important example how to remove first and last element from an array in javascript. if you want to see example of how to remove first and last element of array in javascript then you are a right place. it's simple example of to remove first and last element in array using javascript.

In this tutorial, I am going to explain to you to remove first and the last element from an array. To remove the first and last element from an array, we can use the shift() and pop() methods in JavaScript.The shift() and pop() methods can also return the removed element.

In the second example we have another method to remove the first and the last elements of an array. this method's name is the slice() method.slice() method by passing 1, -1 as arguments, slicing starts from index 1 and ends before the last index (-1 represents the last element index).

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title> How to Remove First and Last Element from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1> How to Remove First and Last Element from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            const fruits = ["apple","banana","grapes","mango"];
            fruits.shift(); // removes first element...
            ruits.pop(); // removes last element...

            //Give output to console...
            console.log(fruits);
        </script>
    </body>
</html>
Output:
['banana', 'grapes']
Example: 2 index.html
<!DOCTYPE html>
<html>
    <head>
        <title> How to Remove First and Last Element from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1> How to Remove First and Last Element from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            const fruits = ["apple","banana","grapes","mango"];
            const sliced = fruits.slice(1,-1)

            //Give output to console...
            console.log(sliced);
        </script>
    </body>
</html>
Output:
['banana', 'grapes']
I hope it will help you...
#Javascript