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"]
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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"]
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Use splice(startPosition, deleteCount)
array.splice(-1)
Show code snippet
var array = ['abc','def','ghi','123'];
var removed = array.splice(-1); //last item
console.log( 'array:', array );
console.log( 'removed:', removed );
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Array.prototype.filter will create and return a new array consisting of elements that match the predicate.
function removeByIndex(array, index) {
return array.filter(function (el, i) {
return index !== i;
});
}
Even shorter with ECMAScript 6:
var removeByIndex = (array, index) => array.filter((_, i) => i !== index);
You can use the es6 spread operator and Array.prototype.splice
var arr = [{id:1, name:'name'},{id:2, name:'name'},{id:3, name:'name'}];
let newArr = [...arr]
newArr.splice(index)
The spread operator copies the array and splice changes the contents of an array by removing or replacing existing elements and/or adding new elements
pop() function also removes last element from array, so this is what you want(Demo on JSFiddle):
var abc = ['a', 'b', 'c', 'd'];
abc.pop()
alert(abc); // a, b, c
Do this
abc = abc.splice(0, abc.length-1)
Edit: It has been pointed out that this actually returns a new array(albeit with the same variable name).
If you want to return the same array, you'll have to make your own function
function popper(arr) {
arr.pop();
return arr;
}