Write a function that takes an array as input and returns a new array with the last element removed. The original array should not be modified. Your solution should return a new array that contains all the elements of the input array except for the last one.
Input: array = [1, 2, 3, 4, 5]
Output: [1, 2, 3, 4]
function removeLastElementWithSlice(arr) {
return arr.slice(0, -1);
}
const array1 = [1, 2, 3, 4, 5];
removeLastElementWithSlice(array1); //output: [1, 2, 3, 4]
function removeLastElementWithFilter(arr) {
return arr.filter((_, index) => index < arr.length - 1);
}
const array1 = [1, 2, 3, 4, 5];
removeLastElementWithFilter(array1); //output: [1, 2, 3, 4]
function removeLastElementWithArrayFrom(arr) {
return Array.from(arr).slice(0, -1);
}
const array1 = [1, 2, 3, 4, 5];
removeLastElementWithArrayFrom(array1); //output: [1, 2, 3, 4]
function removeLastElementWithMap(arr) {
return arr.map((item, index) => (index < arr.length - 1 ? item : null)).filter(item => item !== null);
}
const array1 = [1, 2, 3, 4, 5];
removeLastElementWithMap(array1); //output: [1, 2, 3, 4]
function removeLastElementWithReduce(arr) {
return arr.reduce((acc, item, index) => {
if (index < arr.length - 1) acc.push(item);
return acc;
}, []);
}
const array1 = [1, 2, 3, 4, 5];
removeLastElementWithReduce(array1); //output: [1, 2, 3, 4]
function removeLastElementWithForLoop(arr) {
let newArray = [];
for (let i = 0; i < arr.length - 1; i++) {
newArray.push(arr[i]);
}
return newArray;
}
const array1 = [1, 2, 3, 4, 5];
removeLastElementWithForLoop(array1); //output: [1, 2, 3, 4]
function removeLastElementWithForOf(arr) {
let newArray = [];
let index = 0;
for (const item of arr) {
if (index < arr.length - 1) {
newArray.push(item);
}
index++;
}
return newArray;
}
const array1 = [1, 2, 3, 4, 5];
removeLastElementWithForOf(array1); //output: [1, 2, 3, 4]
function removeLastElementWithSplice(arr) {
return arr.slice(0, -1);
}
const array1 = [1, 2, 3, 4, 5];
removeLastElementWithSplice(array1); //output: [1, 2, 3, 4]
function removeLastElementWithConcat(arr) {
return [].concat(arr.slice(0, -1));
}
const array1 = [1, 2, 3, 4, 5];
removeLastElementWithConcat(array1); //output: [1, 2, 3, 4]
function removeLastElementWithDestructuring(arr) {
const [ ...newArray ] = arr;
newArray.pop(); // Removes the last element
return newArray;
}
const array1 = [1, 2, 3, 4, 5];
removeLastElementWithDestructuring(array1); //output: [1, 2, 3, 4]