typescript how to remove the last element of an array and return the result
In TypeScript (or JavaScript), you can remove the last element of an array and return the result using the pop
method. The pop
method removes the last element from an array and returns that element. If you want to return the modified array instead, you can simply call the pop
method and then return the array.
Here's an example:
function removeLastElement<T>(arr: T[]): T[] {
arr.pop(); // Remove the last element
return arr; // Return the modified array
}
// Example usage:
const numbers = [1, 2, 3, 4, 5];
const modifiedNumbers = removeLastElement(numbers);
console.log(modifiedNumbers); // Output: [1, 2, 3, 4]
In this example, the removeLastElement
function takes an array arr
of generic type T
and removes the last element using the pop
method. It then returns the modified array.
If you also want to return the removed element along with the modified array, you can do so by returning a tuple:
function removeLastElement<T>(arr: T[]): [T[], T | undefined] {
const removedElement = arr.pop(); // Remove the last element
return [arr, removedElement]; // Return the modified array and the removed element
}
// Example usage:
const numbers = [1, 2, 3, 4, 5];
const [modifiedNumbers, removedElement] = removeLastElement(numbers);
console.log(modifiedNumbers); // Output: [1, 2, 3, 4]
console.log(removedElement); // Output: 5
In this version, the removeLastElement
function returns a tuple containing the modified array and the removed element. This way, you can access both the modified array and the removed element separately.