最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pop the last item off of an array without using built in the array.pop() function - Stack Overflow

programmeradmin3浏览0评论

I'm trying to plete 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])

I'm trying to plete 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!

Share Improve this question edited Nov 23, 2018 at 20:17 Scott Marcus 65.9k6 gold badges53 silver badges80 bronze badges asked Nov 23, 2018 at 20:11 Marsden MarsMarsden Mars 451 silver badge6 bronze badges 3
  • 2 Try with slice() ... developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Asons Commented Nov 23, 2018 at 20:12
  • 1 simple, array.reverse().shift() then reverse it again.. – rlemon Commented Nov 23, 2018 at 20:15
  • 1 First check the array length. If it is zero, return undefined. Otherwise, save the last array element in a local variable (using length-1 to access it). Then decrement the length, and return that local variable. – Michael Geary Commented Nov 23, 2018 at 20:21
Add a ment  | 

6 Answers 6

Reset to default 5

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);

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())

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);

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);

Edit from ment

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);

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/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 ] )( [ ] )( )( [ , , , ] )

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.

发布评论

评论列表(0)

  1. 暂无评论