Array.prototype.pop() by JavaScript convention.
let fruit = ['apple', 'orange', 'banana', 'tomato'];
let popped = fruit.pop();
console.log(popped); // "tomato"
console.log(fruit); // ["apple", "orange", "banana"]
Answer from Stuart Kershaw on Stack OverflowArray.prototype.pop() by JavaScript convention.
let fruit = ['apple', 'orange', 'banana', 'tomato'];
let popped = fruit.pop();
console.log(popped); // "tomato"
console.log(fruit); // ["apple", "orange", "banana"]
Use splice(startPosition, deleteCount)
array.splice(-1)
var array = ['abc','def','ghi','123'];
var removed = array.splice(-1); //last item
console.log( 'array:', array );
console.log( 'removed:', removed );
You can use both Array.prototype.splice(start) and Array.prototype.slice(start, end) depending on if you want to mutate the array or not
Mutable method
Using Array.prototype.splice:
The splice() method of Array instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
const arr = ['a', 'b', 'c', 'd', 'e'];
const n = 3;
arr.splice(n - arr.length); // returns: ['d', 'e']
console.log(arr); // output: ['a', 'b', 'c']
Immutable method
Using Array.prototype.slice:
The slice() method of Array instances returns a shallow copy of a portion of an array into a new array object selected from
starttoend(endnot included) wherestartandendrepresent the index of items in that array. The original array will not be modified.
const arr = ['a', 'b', 'c', 'd', 'e'];
const n = 3;
const result = arr.slice(0, n - arr.length);
console.log(result); // output: ['a', 'b', 'c']
console.log(arr); // output: ['a', 'b', 'c', 'd', 'e'] (arr is not mutated)
const arr = ['a', 'b', 'c', 'd', 'e'];
const dynamic = 3;
arr.splice(dynamic - arr.length);
console.log(arr);
To keep the first ten items:
if (theArray.length > 10) theArray = theArray.slice(0, 10);
or, perhaps less intuitive:
if (theArray.length > 10) theArray.length = 10;
To keep the last ten items:
if (theArray.length > 10) theArray = theArray.slice(theArray.length - 10, 10);
You can use a negative value for the first parameter to specify length - n, and omitting the second parameter gets all items to the end, so the same can also be written as:
if (theArray.length > 10) theArray = theArray.slice(-10);
The splice method is used to remove items and replace with other items, but if you specify no new items it can be used to only remove items. To keep the first ten items:
if (theArray.length > 10) theArray.splice(10, theArray.length - 10);
To keep the last ten items:
if (theArray.length > 10) theArray.splice(0, theArray.length - 10);
Use the function array.splice(index, count) to remove count elements at index. To remove elements from the end, use array1.splice(array1.length - 10, 1);