How to use Array slice() Method In Javascript
In this appraoch we are using Array.slice() method. This method returns a new array containing the selected elements. This method selects the elements that start from the given start argument and end at, but excludes the given end argument.
Syntax:
array.slice(start, end)
Parameters:
- start: This parameter is optional. It specifies the integer from where to start the selection (the first element is at index 0). Negative numbers are used to select from the end of the array. If not used, it acts like “0”
- end: This parameter is optional. It specifies the integer from where to end the selection. If not used, all elements from the start to the end of the array will be included in the selection. Negative numbers are used to select from the end.
Return value:
Returns a new Array, having the selected items.
Example: This example does not remove the last item from the array but returns a new array in which the item is removed, using the slice() method.
// Input array
let array = [34, 24, 31, 48];
// Display input array
console.log("Array = [" + array + "]");
// Function to remove last element
function gfg_Run() {
// Display output
console.log(
"Remaining array = [" + array.slice(0, -1) + "]");
}
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