Remove last element from an array in JavaScript
In this tutorial, we will learn how to remove the last element from an array in JavaScript.
Removing the last element from an array in JavaScript
Variables used in code
- arr – array
let arr = ['This','is','a','Tutorial','in','CodeSpeedy']
Method 1
We use the built-in slice()
function to get all elements from an array except the last one.
arr = arr.slice(0,-1)
Method 2
Here, we use the pop()
inbuilt function to remove the last element from an array.
arr.pop()
Method 3
We use the filter()
inbuilt function to extract all elements from the array except the last one.
arr = arr.filter((item,id)=> id < arr.length-1)
Method 4
To remove the last element from an array, we use the built-in splice()
function.
arr.splice(-1)
Output
console.log(arr)
["This", "is", "a", "Tutorial", "in"]
You can also read: Convert first letters of a string to uppercase in JavaScript
Leave a Reply