How to useArray.filter() Method in Javascript
The Array.filter() method creates a new array with all elements that pass the test implemented by the provided function. We can use this method to exclude the last element from the array.
Syntax:
array.filter(callback(element, index, array), thisArg);
Example: In this example, we’ll use the Array.filter() method to create a new array that excludes the last element.
// Input array
let array = [34, 24, 31, 48];
// Display input array
console.log("Array = [" + array + "]");
// Function to remove last element
function gfg_Run() {
// Create a new array without the last element
let newArray = array.filter((_, index) => index !== array.length - 1);
// Display output
console.log("Remaining array = [" + newArray + "]");
}
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