JavaScript - Delete last Occurrence from JS Array
These are the following ways to remove the last Item from the given array:
1. Using pop() Method (Simple and Easiest Method for Any Array)
The pop() method is used to get the last element of the given array it can also be used to remove the last element from the given array.
let a = [34, 24, 31, 48];
a.pop();
console.log(a);
Output
[ 34, 24, 31 ]
2. Using Array splice() Method (Simple for Long Array)
This method uses Array.splice() method that adds/deletes items to/from the array and returns the deleted item(s).
let a = [34, 24, 31, 48];
a.splice(-1, 1);
console.log(a);
Output
[ 34, 24, 31 ]
3. Using Array slice() Method(Efficient for Any Array)
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.
let a = [34, 24, 31, 48];
console.log(a.slice(0, -1));
Output
[ 34, 24, 31 ]
4. Using Array length Property(Simple and Easy Way For Long Array)
The array length property in JavaScript is used to set or return the number of elements in an array.
let a = [34, 24, 31, 48];
a.length = a.length - 1;
console.log(a);
Output
[ 34, 24, 31 ]
5. Using Spread Operator (...)(Efficient for Short Array)
The spread operator (...) is a concise way to manipulate arrays. To remove the last element from an array, you can use the spread operator along with array destructuring.
let a = [34, 24, 31, 48];
let res = [...a.slice(0, -1)]
console.log(res);
Output
[ 34, 24, 31 ]
6. Using Array.reduceRight() Method(Efficient for Short Array)
The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. This method can be utilized to create a new array excluding the last element.
let a = [34, 24, 31, 48];
let a1 = a.reduceRight((ac, c, idx) => {
if (idx !== a.length - 1) {
ac.unshift(c);
}
return ac;
}, []);
console.log(a1);
Output
[ 34, 24, 31 ]