How to Remove First and Last Element from Array using JavaScript?
Removing the first and last elements from an array is a common operation. This can be useful in various scenarios, such as data processing, filtering, or manipulation.
Example:
Input: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Output: [ 2, 3, 4, 5, 6, 7, 8, 9 ]
Removing first and last element in array can be done using below approaches:
Table of Content
Using Slice() Method
The approach involves creating a new array by extracting a portion of an existing array. The slice() method is used to take elements starting from the second position up to the second-to-last position. This excludes the first and last elements of the original array. The resulting new array contains all the elements from the second to the penultimate one of the original array.
Example: This example shows that the slice() method can be used to remove the first and last elements from an array.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newArray = arr.slice(1, -1);
console.log(newArray);
Output
[ 2, 3, 4, 5, 6, 7, 8, 9 ]
Using Splice() Method
The approach involves populating an array with a sequence of numbers and then removing the first and last elements if the array contains more than one element. The array is initially empty and numbers from 0 to 9 are added to it. After ensuring the array has more than one element, the splice() method is used to remove the first element and then the last element. The resulting array excludes the original first and last elements.
Example: This example shows that the splice() method can be used to remove elements from an array.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
if (arr.length > 1) {
arr.splice(0, 1);
arr.splice(arr.length - 1, 1);
}
console.log(arr);
Output
[ 2, 3, 4, 5, 6, 7, 8, 9 ]