How to use array.reduce() Method In Javascript
The array.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array and the return value of the function is stored in an accumulator.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr), initialValue )
Example: This example removes the last item from the array using the arr.reduce() method.
// Input array
let array = [34, 24, 31, 48];
// Display input array
console.log("Array = [" + array + "]");
// Function to remove last element
function gfg_Run() {
array = array.filter((item, i) => i != (array.length - 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