This post will discuss how to remove the last element from an array in JavaScript. Show 1. Using Array.prototype.pop() functionThe standard way to remove the last element from an array is with the pop() method. This method works by modifying the original array. The following code creates an array containing five elements, then removes its last element. 1 2 3 4 5 6 7 8 var arr = [1, 2, 3, 4, 5];
var last = arr.pop(); console.log(arr);
/* Output: [ 1, 2, 3, 4 ] */ Download Run Code 2. Using Array.prototype.splice() functionThe splice() method is often used to in-place remove existing elements from the array or add new elements to it. The following example demonstrates the usage of the 1 2 3 4 5 6 7 8 var arr = [1, 2, 3, 4, 5];
arr.splice(arr.length - 1); console.log(arr);
/* Output: [ 1, 2, 3, 4 ] */ Download Run Code 1 2 3 4 5 6 7 8 9 var arr = [1, 2, 3, 4, 5]; var n = 3;
arr.splice(arr.length - n); console.log(arr);
/* Output: [ 1, 2 ] */ Download Run Code 3. Using Lodash LibraryIf you’re using the Lodash JavaScript library in your project, you can use the method, which returns everything but the last element of the array. Note that this doesn’t modify the original array but returns a new array. 1 2 3 4 5 6 7 8 9 var _ = require('lodash');
var arr = [1, 2, 3, 4, 5]; arr = _.initial(arr); console.log(arr);
/* Output: [ 1, 2, 3, 4 ] */ Download Code 4. Using Underscore LibraryAlternatively, to remove the last 1 2 3 4 5 6 7 8 9 10 11 var _ = require('underscore');
var arr = [1, 2, 3, 4, 5]; var n = 3;
arr = _.initial(arr, n); console.log(arr);
/* Output: [ 1, 2 ] */ Download Code That’s all about removing the last element from an array in JavaScript. How do I remove the last 3 elements from a list?Using del
Another efficient, yet simple approach to delete the last element of the list is by using the del statement. The del operator deletes the element at the specified index location from the list. To delete the last element, we can use the negative index -1.
How to remove last n elements from array in PHP?To remove the last element or value from an array, array_pop() function is used. This function returns the last removed element of the array and returns NULL if the array is empty, or is not an array.
How to remove last two values from array in JavaScript?Use the splice() method to remove the last 2 elements from an array, e.g. arr. splice(arr. length - 2, 2) . The splice method will delete the 2 last elements from the array and return a new array containing the deleted elements.
|