Reputation: 45
I'm trying to complete a problem that involves removing the last item of an array without using the built-in .pop function. Here is the full problem...
Write a function which accepts an array.
The function should remove the last value in the array and return the value removed or undefined if the array is empty.
Do not use the built in Array.pop() function!
Example:
var arr = [1, 2, 3, 4];
pop(arr); // 4
I figured out how to grab the last number with the following code but this obviously doesn't solve the problem.
function pop (array){
for (i=array.length-1; i>array.length-2; i--){
array = array[i]
} return array
}
pop ([1,2,3,4])
Thanks in advance!
Upvotes: 1
Views: 3444
Reputation: 762
You could use Array.splice()
function pop(arr) {
return arr.splice(-1)[0];
}
This will delete the last item in the array and return it.
Upvotes: 0
Reputation: 1574
EDIT: This includes a null and empty check.
var array = [1, 2, 3, 4, 5];
function pop(array) {
return array && array.splice(-1)[0]
}
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(array);
Upvotes: 2
Reputation: 92460
It seems like simple is better in this case:
const example = [1,2,3,4];
function pop(arr) {
return arr && arr.splice(-1)[0]
}
console.log(pop(example))
console.log(pop(example))
console.log(pop(example))
console.log(pop(example))
console.log(pop(example))
// edge case: should it return undefined or should it throw?
console.log(pop())
Upvotes: 4
Reputation:
Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]])
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
...
Return value: An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
What this means is that so long as the input to the function is an instance of Array, we can call Array#splice(-1)
to remove the last element. If there are no elements, this will return an empty array. Because we will always be getting either an array with one element or an empty array, we can access the first element using [0]
. If the array is empty, this will be undefined
.
So, check that that input is an array, then return Array#splice(-1)[0]
if it is or undefined
if it is not.
function pop(input) {
let output;
if(input instanceof Array) {
output = input.splice(-1)[0]
}
return output
}
function test(input) {
console.log({
before: input && Array.from(input),
popped: pop(input),
after: input
})
return test
}
test( [ 1, 2, 3, 4 ] )( [ 1 ] )( [ ] )( )( [ , , , ] )
Upvotes: 0
Reputation: 1619
I think what you are looking for is Array.prototype.slice(). You can use the length property of the array to determine whether it is empty and then return the last entry using slice.
const example = [1,2,3,4];
const emptyExample = [];
const pop = group => group.length > 0
? group.slice(group.length - 1)[0]
: undefined;
const answers = [ pop(example), pop(emptyExample) ];
console.log(answers);
Example should remove from the array while returning last entry so Array.prototype.splice is probably the better function here.
const example = [1,2,3,4];
const emptyExample = [];
const pop = group => (Array.isArray(group) && group.length > 0)
? group.splice(group.length - 1, 1)[0]
: undefined;
const initialExample = [ ...example ];
const answers = [
pop(example),
pop(emptyExample),
{ initialExample, updatedExample: example, emptyExample }
];
console.log(answers);
Upvotes: 0
Reputation: 65835
A much simpler solution is to just decrease the length of the array by one. No need to create a second array.
function pop (array){
let last = array[array.length-1]; // Store last item in array
array.length = array.length > 0 ? array.length - 1 : 0; // Decrease length
return last; // Return last item
}
// Test function
function logger(ary){
console.log("Original array: " + ary.join(", "), "\n\tItem popped off: " + pop(ary), "\n\tArray contents now: " + ary.join(", "));
}
// Tests
var ary = [1,2,3,4]; logger(ary);
var ary = ["red", "white", "blue", "green"]; logger(ary);
var ary = ["onlyItem"]; logger(ary);
var ary = []; logger(ary);
var ary = [false]; logger(ary);
Upvotes: 5