How to use Array splice() Method In Javascript
This method uses Array.splice() method that adds/deletes items to/from the array and returns the deleted item(s).
Syntax:
array.splice(index, number, item1, ....., itemN)
Parameters:
- index: This parameter is required. It specifies the integer at what position to add/remove items, Negative values are used to specify the position from the end of the array.
- number: This parameter is optional. It specifies the number of items to be removed. 0 means, nothing to remove.
- item1, ….., itemN: This parameter is optional. This specifies the new item(s) to be added to the array.
Return value:
Returns a new Array, having the removed items.
Example: This example removes the last item from the array using the splice() method.
// Input array
let array = [34, 24, 31, 48];
// Display array
console.log("Array = [" + array + "]");
// Funciton to remove last element
function gfg_Run() {
array.splice(-1, 1);
// Display Output
console.log(
"Remaining array = [" + array + "]");
}
gfg_Run()
Output
Array = [34,24,31,48] Remaining array = [34,24,31]
Remove the last Item From an Array in JavaScript
Removing the last item from an array in JavaScript is a fundamental operation often encountered in array manipulation tasks. It involves eliminating the last element of an array, which can be useful for dynamically adjusting array contents based on various conditions or requirements within a program.
Methods to Remove the Last Element from an Array:
Table of Content
- Using Array splice() Method
- Using Array slice() Method
- Using Array pop() Method
- Using array.reduce() Method
- Using Array.length
- Using Array.filter() Method
Contact Us