This article will provide the procedure to remove the first and last array’s element in JavaScript.
How to Remove/Omit First and Last Array Elements in JavaScript?
To remove/omit the first and last elements in the given array in JavaScript, you can use:
We will now go through each of the mentioned methods one by one!
Method 1: Remove/Omit First and Last Array Elements in JavaScript Using shift() and pop() Methods
In JavaScript, the “shift()” method is used to omit the first array element. Whereas the “pop()” method omits the last array element. These methods can be used in combination to remove the first and last array elements.
Syntax
Here, “array” refers to a defined array on which the shift() and pop() methods will be applied to remove the first and last array elements, respectively.
Look at the stated example for the demonstration.
Example
In the following example, initialize an array named “remArr” with integer and string value in it:
Now, we will apply the “shift()” method to remove the first element “1” from an array and display it on the console using the “console.log()” method:
console.log("Array after removal of first element is:", remArr)
After that, we will use the “pop()” method to remove the last element “a” from an array and display it:
console.log("Array after removal of last element is:", remArr)
Lastly, print out the update array on the console:
Output
Method 2: Remove First and Last Array Elements in JavaScript Using slice() Method
In JavaScript, the “slice()” method slices up the array elements and returns them as a new array. You can apply this method to slice the first and last array elements by accessing their indexes and removing them from an array.
Syntax
Here, “start” and “end” refer to the first and last index of the array.
The following example explains the stated concept:
Example
Now, we will apply the “slice()” method to the “remArr” string and refer to the start and end indexes “1” and “-1”, respectively. This will result in removing the elements at first and last indexes from the given array:
var firstLast= remArr.slice(1, -1)
Lastly, we will display the resultant array on the console:
Output
We have provided all the simplest methods to remove the first and the last element in the array in JavaScript.
Conclusion
For removing the first and the last array elements, you can use the “shift()” and “pop()” methods for removing the first and last elements in an array respectively and the “slice()” method to specify the index of the element in its argument, which needs to be removed. Both methods change the length of the original array. This write-up explained the methods to remove the first and last array elements in JavaScript.